{-# OPTIONS_GHC -O2 #-}
{-# LANGUAGE ForeignFunctionInterface #-}

-- Codeforces 404B

import Foreign
import Foreign.C.String
import Foreign.C.Types
import Data.Fixed (mod') -- important !!
import Control.Applicative

main :: IO ()
main = do
    [a, d] <- fmap (map read . words) getLine
    n <- fmap read getLine
    newCString "%.8lf %.8lf\n" >>= solve a d n

foreign import ccall "stdio.h printf"
    c_printf :: CString -> Double -> Double -> IO CInt

solve :: Double -> Double -> Int -> CString -> IO ()
solve a d n format = mapM_ (ps . handle . (*) d . fromIntegral) [1..n] where
    handle p = case p `mod'` (4*a) of
        q | q < a -> (q, 0)
        q | q < 2 * a -> (a, q-a)
        q | q < 3 * a -> (3*a-q, a)
        q | otherwise -> (0, 4*a-q)
    ps (a, b) = c_printf format a b where

{-# OPTIONS_GHC -O2 #-}
{-# LANGUAGE BangPatterns, OverloadedStrings #-}
import Control.Applicative
import Control.Monad
import qualified Data.ByteString.Char8 as B
import Foreign.C.Types
import Foreign.C.String

main = do
  [a,d,n] <- map read.words <$> getContents
  solve (round n) a d

foreign import ccall unsafe "stdio.h printf"
  c_printf :: CString -> Double -> Double -> IO ()

putAnswer :: Double -> Double -> IO ()
putAnswer x y = B.useAsCString "%f %f\n" $ \fmt-> do
  c_printf fmt x y

solve :: Int -> Double -> Double -> IO ()
solve n a d = go 1
   where
     go i = do
       when (i<=n) $ do
         let q = fromIntegral.floor $ (fromIntegral i*d) / (4*a)
             x = fromIntegral i*d - q*4*a
         if x <= 1*a then  putAnswer x 0
         else if x <= 2*a then putAnswer a (x-a)
         else if x <= 3*a then putAnswer (a-(x-2*a)) a
         else putAnswer 0 (a-(x-3*a))
         go (i+1)

{-# LANGUAGE ForeignFunctionInterface #-}

import Foreign
import Foreign.C.String
import Foreign.C.Types
import Data.Fixed
import qualified Data.ByteString.Lazy as B
import qualified Data.ByteString.Lazy.Char8 as B8
import Control.Applicative
import System.IO
import Control.DeepSeq
import Text.Printf

main = do
    inp <- words <$> getContents
    solve inp

foreign import ccall "stdio.h printf"
    c_printf :: CString -> Double -> Double -> IO CInt

solve [sa, sd, sn] = do
    format <- newCString "%.6lf %.6lf\n"
    let a = read sa :: Double
        d = read sd :: Double
        n = read sn :: Int
        ps :: (Double, Double) -> IO ()
        ps (a, b) = do
            c_printf format a b
            return ()

        dtoc p = case mod' p (4 * a) of
            q | q < a     -> (q, 0)
            q | q < 2 * a -> (a, q - a)
            q | q < 3 * a -> (3 * a - q, a)
            q | otherwise -> (0, 4 * a - q)
    mapM_ (ps . dtoc . (*)d . fromIntegral) [1 .. n]

-- Codeforces 404B

import Data.List (intercalate)

main :: IO ()
main = do
    [a, d] <- fmap (map read . words) getLine
    n <- fmap read getLine
    putStrLn $ intercalate "\n" $ solve a d n

solve :: Double -> Double -> Int -> [String]
solve a d n = map path [1..n] where
    path :: Int -> String
    path i = case k `mod` 4 of {
        0 -> str h 0;
        1 -> str a h;
        2 -> str (a-h) a;
        3 -> str 0 (a-h);
    } where
        l = (fromIntegral i) * d
        k = floor (l / a) :: Int
        h = l - (fromIntegral k) * a
        str :: Double -> Double -> String
        str x y = (show x) ++ " " ++ (show y)


import Data.List
ntobits = reverse . go 8 where
  go 0 _ = []
  go i n = odd n : go (i-1) (n `div` 2)
tobits ns = ns >>= ntobits
ipwords [] = []
ipwords s = case span(/='.') s of
  (l,r) -> l : ipwords (drop 1 r)
pip=map(foldl(\a c->a*10+fromEnum c-fromEnum '0')0).ipwords

frombitsn=foldl(\n b-> n*2+fromEnum b)0
frombits=map frombitsn.unfoldr uf where
  uf [] = Nothing
  uf l = Just $ splitAt 8 l
pr m=intercalate "."$map show$frombits$replicate m True ++ replicate (32-m) False
bsearch f a b | a + 1 == b = a
 | f c = bsearch f a c
 | otherwise = bsearch f c b where
   c = (a + b)`div`2
s k l
  | k == g r = pr r
  | otherwise = "-1"
  where
  r = min 31 $ bsearch f 0 32 + 1
  g i = length(group$map(take i)l)
  f i = g i >= k
solve(hl:rl)=s((!!1).map read.words$hl).sort.map(tobits.pip)$rl
main=interact$solve.lines

import Data.ByteString.Char8 as BS (getLine, readInt, split, words)
import Data.Bits ((.&.), shiftL)
import Data.Maybe (fromJust)
import Data.List (intersperse)
import Data.Set as Set (fromList, size)

main = do
    [n, k] <- fmap (map readInt' . BS.words) BS.getLine
    ips <- fmap (map fromIP) $ sequence $ replicate n BS.getLine
    let subnets = scanl1 (+) $ map (1 `shiftL`) [31,30..0]
    case filter (check k ips) subnets of
        []       -> print (-1)
        subnet:_ -> putStrLn $ toIP subnet

check k ips subnet = (==k) $ Set.size $ Set.fromList $ map (subnet .&.) ips

readInt' = fst . fromJust . BS.readInt

fromIP s = sum $ zipWith (*) (map (256^) [3,2,1,0]) $ map readInt' $ BS.split '.' s

toIP x = concat $ intersperse "." $ reverse $ map (show . (`mod` 256)) $ scanl div x $ replicate 3 256

{-# LANGUAGE GeneralizedNewtypeDeriving #-}
import Data.Bits
import Data.List
import Data.Maybe
import Data.Word
import qualified Data.ByteString.Char8 as C

newtype IP = IP Word32
  deriving (Eq, Ord, Num, Bits)

instance Show IP where
  show (IP ip) = intercalate "." $ map show $
    reverse $ map (`mod`256) $ take 4 $ iterate (`div`256) $ ip

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

parse :: C.ByteString -> IP
parse s = IP $ foldl1 (\i j -> (i * 256 + j)) $ map (fromIntegral . readInt) $ C.split '.' s

clz :: (Num a, Bits a) => a -> Int
clz x
  | x == 0    = n
  | otherwise = m - until (testBit x) pred m
  where
    n = bitSize x
    m = n - 1

main :: IO ()
main = do
  (sn:sm:s) <- fmap C.words C.getContents
  let _ = readInt sn
      m = readInt sm
      a = sort $ map parse s
      b = [i | i <- masks, let j = map (.&. i) a, length (group j) == m]
  if null b
    then putStrLn "-1"
    else putStrLn $ show $ head b
  where
    masks = scanl1 (.|.) $ map (IP . bit) $ [31, 30 .. 0]

import Data.List
ntobits = reverse . go 8 where
  go 0 _ = []
  go i n = odd n : go (i-1) (n `div` 2)
tobits ns = ns >>= ntobits
ipwords [] = []
ipwords s = case span(/='.') s of
  (l,r) -> l : ipwords (drop 1 r)
pip=map read.ipwords

frombitsn=foldl(\n b-> n*2+fromEnum b)0
frombits=map frombitsn.unfoldr uf where
  uf [] = Nothing
  uf l = Just $ splitAt 8 l
pr[]="-1"
pr(m:_)=intercalate "."$map show$frombits$replicate m True ++ replicate (32-m) False
s k l=pr$filter(\i->k==length(nub$map(take i)l))[0..32] where
solve(hl:rl)=s((!!1).map read.words$hl).map(tobits.pip)$rl
main=interact$solve.lines

import Data.List
ntobits = reverse . go 8 where
  go 0 _ = []
  go i n = odd n : go (i-1) (n `div` 2)
tobits ns = ns >>= ntobits
ipwords [] = []
ipwords s = case span(/='.') s of
  (l,r) -> l : ipwords (drop 1 r)
pip=map(foldl(\a c->a*10+fromEnum c-fromEnum '0')0).ipwords

frombitsn=foldl(\n b-> n*2+fromEnum b)0
frombits=map frombitsn.unfoldr uf where
  uf [] = Nothing
  uf l = Just $ splitAt 8 l
pr m=intercalate "."$map show$frombits$replicate m True ++ replicate (32-m) False
bsearch f a b | a + 1 == b = a
 | f c = bsearch f a c
 | otherwise = bsearch f c b where
   c = (a + b)`div`2
s k l
  | k == g r = pr r
  | otherwise = "-1"
  where
  r = bsearch f 1 32
  g i = length(group$map(take i)l)
  f i = k >= g i
solve(hl:rl)=s((!!1).map read.words$hl).sort.map(tobits.pip)$rl
main=interact$solve.lines

import Data.List
ntobits = reverse . go 8 where
  go 0 _ = []
  go i n = odd n : go (i-1) (n `div` 2)
tobits ns = ns >>= ntobits
ipwords [] = []
ipwords s = case span(/='.') s of
  (l,r) -> l : ipwords (drop 1 r)
pip=map read.ipwords

frombitsn=foldl(\n b-> n*2+fromEnum b)0
frombits=map frombitsn.unfoldr uf where
  uf [] = Nothing
  uf l = Just $ splitAt 8 l
pr[]="-1"
pr(m:_)=intercalate "."$map show$frombits$replicate m True ++ replicate (32-m) False
s k l=pr$filter(\i->k==length(nub$map(take k)l))[0..32]
solve(hl:rl)=s((!!1).map read.words$hl).map(tobits.pip)$rl
main=interact$solve.lines

import Data.List
ntobits = reverse . go 8 where
  go 0 _ = []
  go i n = odd n : go (i-1) (n `div` 2)
tobits ns = ns >>= ntobits
ipwords [] = []
ipwords s = case span(/='.') s of
  (l,r) -> l : ipwords (drop 1 r)
pip=map(foldl(\a c->a*10+fromEnum c-fromEnum '0')0).ipwords

frombitsn=foldl(\n b-> n*2+fromEnum b)0
frombits=map frombitsn.unfoldr uf where
  uf [] = Nothing
  uf l = Just $ splitAt 8 l
pr m=intercalate "."$map show$frombits$replicate m True ++ replicate (32-m) False
bsearch f a b | a + 1 == b = a
 | f c = bsearch f a c
 | otherwise = bsearch f c b where
   c = (a + b)`div`2
s k l
  | k == g r = pr r
  | otherwise = "-1"
  where
  r = min 31 $ bsearch f 1 32 + 1
  g i = length(group$map(take i)l)
  f i = g i >= k
solve(hl:rl)=s((!!1).map read.words$hl).sort.map(tobits.pip)$rl
main=interact$solve.lines


import Control.Monad (replicateM_)
import Data.Int (Int64)

step :: Int64 -> [Int] -> [Int]
step k li = let
  p = minimum li
  q = maximum li
  in  if  even k  then  map (subtract p) li  else  map (q-) li

main :: IO ()
main = do
  t <- read <$> getLine
  replicateM_ t $ do
    [_n, k] <- map read . words <$> getLine
    a <- map read . words <$> getLine
    putStrLn . unwords $ map show (step k a)

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

main = getLine >>= flip replicateM_ test . read

test = do
  [n, k] <- map read . words <$> getLine
  as <- map read . words <$> getLine
  if odd k
    then putStrLn $ unwords $ map show $ apply as
    else putStrLn $ unwords $ map show $ apply $ apply as

apply as = (maximum as -) <$> as

{-# LANGUAGE OverloadedStrings #-}

import Prelude
import Control.Monad
import Data.Functor
import Data.List
import Data.Maybe
import Data.Int
import Data.Char
import qualified Data.ByteString.Char8 as B8
import Text.Printf

readIntB8 :: B8.ByteString -> Int
readIntB8 = fst . fromJust . B8.readInt

readInt64B8 :: B8.ByteString -> Int64
readInt64B8 = fromInteger . fst . fromJust . B8.readInteger

step :: [Int] -> [Int]
step as = map (\x -> maxA - x) as
    where
        maxA = foldr1 max as

solve :: Int64 -> Int64 -> [Int] -> [Int]
solve n k as =
        if ((k - 1) `mod` 2) == 0
            then firstStepped
            else secondStepped
    where
        firstStepped = step as
        secondStepped = step firstStepped

main :: IO ()
main = do
    t <- readIntB8 <$> B8.getLine
    forM_ [1..t] $ \_ -> do
        [n, k] <- map readInt64B8 <$> B8.words <$> B8.getLine
        as <- map readIntB8 <$> B8.words <$> B8.getLine
        let answer = solve n k as
        forM_ answer $ printf "%d "
        printf "\n"


import Data.List  (find)
import Data.Maybe (fromJust)

minus :: [Int] -> [Int] -> [Int]
minus (x:xs) (y:ys) = case compare x y of
           LT -> x : minus  xs  (y:ys)
           EQ ->     minus  xs     ys
           GT ->     minus (x:xs)  ys
minus  xs     _     = xs

merge :: [Int] -> [Int] -> [Int]
merge (x:xs) (y:ys) = case compare x y of
           LT -> x : merge  xs  (y:ys)
           EQ -> x : merge  xs     ys
           GT -> y : merge (x:xs)  ys
merge  xs     []    = xs
merge  []     ys    = ys

mergeAll :: [[Int]] -> [Int]
mergeAll = foldr (\(x : xs) -> (x : ) . merge xs) []

primes :: [Int]
primes = 2 : 3 : minus [5,7..] (mergeAll [[p*p, p*p+2*p..] | p <- tail primes])

process :: Int -> Int
process d = p * q
    where p = fromJust $ find (>= d + 1) primes
          q = fromJust $ find (>= p + d) primes

main :: IO ()
main = interact (unlines . map (show . process . (read :: String -> Int)) . tail . lines)

module Main where

sieve a b
    |b==[] = []
    |(head b)>a = sieve (a+1) b
    |(head b)==a = (head b):(sieve (a+1) (filter (\e->(e`mod`a)/=0) (tail b)))
    |otherwise = sieve (a+1) (filter (\e->(e`mod`a)/=0) b)

primes=sieve 2 [2..30000]

search_geq (x:xs) b
    | x>=b = x
    | otherwise = search_geq xs b

work t=p*q
    where
        p=search_geq primes $ t+1
        q=search_geq primes $ p+t

run 1 = do
    l1 <- getLine
    putStrLn $ show $ work ((read::String->Integer) l1)

run x = do
    run 1
    run (x-1)

main = do
    l1 <- getLine
    let t = (read::String->Integer) l1
    run t

import Control.Monad

isPrime 2 = True
isPrime n
        | even n = False
        | n < 2 = False
        | any (\x->mod n x==0) $ takeWhile (\x->x*x<=n) [3,5..] = False
        | otherwise = True

solve x = head [i|i<-[x..],isPrime i]

printResult = do
    d <- readLn :: IO Int
    let x = solve $ d + 1
        y = solve $ x + d
    print $ x * y
main = do
    t <- readLn :: IO Int
    replicateM_ t printResult

{-# LANGUAGE DeriveFunctor       #-}
{-# LANGUAGE GADTs               #-}
{-# LANGUAGE OverloadedStrings   #-}
{-# LANGUAGE Safe                #-}
{-# LANGUAGE Strict #-}
{-# LANGUAGE ScopedTypeVariables #-}

import           Control.Arrow              ((>>>))
import           Control.Monad              (MonadPlus (mplus), foldM_, forM_,
                                             guard, join, replicateM,
                                             replicateM_)
import qualified Control.Monad.ST.Strict    as ST
import qualified Control.Monad.State.Strict as S
import qualified Data.Array                 as A
import qualified Data.Array.MArray.Safe     as MA
import qualified Data.Array.ST.Safe         as STA
import qualified Data.Array.Unboxed         as UA
import           Data.Bits
import qualified Data.ByteString.Char8      as B8
import           Data.Char
import           Data.Function              (on)
import           Data.Functor               ((<&>))
import           Data.IORef                 (modifyIORef, newIORef, readIORef)
import           Data.Int
import qualified Data.IntMap                as IM
import           Data.List                  (elemIndices, find, findIndices,
                                             intersect, isPrefixOf, nub, sort,
                                             sortOn)
import qualified Data.Map                   as M
import           Data.Maybe                 (fromJust, fromMaybe, isJust)
import qualified Data.Set                   as S
import           Data.Traversable           (forM)
import           GHC.IO.Handle              (hDuplicateTo)
import           System.IO                  (IOMode (ReadMode, WriteMode),
                                             openFile, stdin, stdout)
import           Text.Printf                (printf)

-- import Debug.Trace (trace)
-- debug = flip trace

readIntB8 :: B8.ByteString -> Int
readIntB8 = B8.readInt >>> (fst . fromJust)

readIntegerB8 :: B8.ByteString -> Integer
readIntegerB8 = B8.readInteger >>> (fst . fromJust)

isPrime :: Int64 -> Bool
isPrime x = all (\d -> x `mod` d /= 0) ds
    where
        sqrtX = floor . sqrt . fromIntegral $ x
        ds = [2 .. sqrtX]

nextPrime :: Int64 -> Int64
nextPrime x = fromJust . find isPrime $ [x..]

solve :: Int64 -> Int64
solve d = x * y
    where
        x = nextPrime (d + 1)
        y = nextPrime (x + d)

main :: IO ()
main = do
    t <- B8.getLine <&> readIntB8
    replicateM_ t $ do
        dd <- B8.getLine <&> readIntegerB8
        let d :: Int64 = fromInteger dd
        let answer = solve d
        printf "%lld\n" answer

import Control.Monad

isPrime 2 = True
isPrime n
        | even n = False
        | n < 2 = False
        | any (\x->mod n x==0) $ takeWhile (\x->x*x<=n) [3,5..] = False
        | otherwise = True

solve x = head [i|i<-[x..],isPrime i]

printResult = do
    d <- readLn :: IO Int
    print $ solve (d+1) * solve (1+2*d)

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

import Control.Monad

printResult = do
    d <- readLn :: IO Int
    print $ (1+d) * (1+2*d)

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


import Control.Applicative ((<$>))
import Data.List (mapAccumL)
import Data.Array (Array, listArray, elems, (!))

zfunc :: Eq a => [a] -> [Int]
zfunc a = elems out
    where
    n = length a :: Int
    mkArray :: [a] -> Array Int a
    mkArray = listArray (0, n - 1)

    arr = mkArray a
    out = mkArray . (n:) . snd $ mapAccumL loop (0, 0) [1..] :: Array Int Int

    loop :: (Int, Int) -> Int -> ((Int, Int), Int)
    loop (l, r) i
        | r < i + 1 = ((i, r'), r' - i)
        | i + out ! (i - l) < r = ((l, r), out ! (i - l))
        | otherwise = ((i, r''), r'' - i)
        where
        next = head . dropWhile (\j -> j < n && arr ! j == arr ! (j - i))
        [r', r''] = map next [[i..], [r..]] :: [Int]

solve :: String -> String
solve [_] = "Just a legend"
solve line = if len /= 0 then take len line else "Just a legend"
    where
    n = length line :: Int
    a = tail . zip [0..] . zfunc $ line :: [(Int, Int)]

    sub = maximum $ map f a :: Int -- longest *strict* substring
        where f (i, k) = if i + k == n then k - 1 else k

    len = maximum $ map f a :: Int
        where f (i, k) = if i + k /= n || sub < k then 0 else k

main = solve <$> getLine >>= putStrLn

{-# LANGUAGE BangPatterns #-}
{-# OPTIONS_GHC -O3 -optc-O3 #-}
import Data.Word

import qualified Data.ByteString as B

data Item = Item { next :: Item, prefix :: Item, ch :: Word8, k :: Int } | NilItem deriving (Eq)

find i c =
	let i' = prefix i in
	if i' == NilItem || ch i == c then i else find i' c

build ind !i s
	| s == B.empty = []
	| otherwise =
		Item (head is) i'' (B.head $ B.tail s) ind : is
		where
			i' = find i (B.head s)
			i'' = if ind /= 1 && ch i' == B.head s then next i' else i'
			is = build (ind + 1) i'' (B.tail s)

main = do
	s1 <- B.getLine

	let	s = B.init s1

	let	i = Item (head is) NilItem (B.head s) 0
		is = build 1 i s
		ps = map (\i -> k $ prefix i) is

		n = B.length s

		p = ps !! (n-1)

	if p == 0
	then putStrLn "Just a legend"
	else
		let ps' = filter (== p) (init ps) in
			if ps' /= []
			then B.putStrLn $ B.take (head ps') s
			else
				let p' = ps !! (p - 1) in
				if p' == 0
				then putStrLn "Just a legend"
				else B.putStrLn $ B.take p' s

{-# LANGUAGE BangPatterns #-}
{-# OPTIONS_GHC -O3 -optc-O3 #-}
import Data.Word

import qualified Data.ByteString as B

data Item = Item { next :: Item, prefix :: Item, ch :: Word8, k :: Int } | NilItem deriving (Eq)

build ind !i s
	| s == B.empty = []
	| otherwise =
		Item (head is) i'' (B.head $ B.tail s) ind : is
		where
			c = B.head s
			i' = find i
			i'' = if ind /= 1 && ch i' == c then next i' else i'
			is = build (ind + 1) i'' (B.tail s)

			find i
				| i' == NilItem || ch i == c = i
				| otherwise = find i'
				where i' = prefix i

main = do
	s1 <- B.getLine

	let	s = B.init s1

	let	i = Item (head is) NilItem (B.head s) 0
		is = build 1 i s
		ps = map (\i -> k $ prefix i) is

		n = B.length s

		p = ps !! (n-1)

	if p == 0
	then putStrLn "Just a legend"
	else
		let ps' = filter (== p) (init ps) in
			if ps' /= []
			then B.putStrLn $ B.take (head ps') s
			else
				let p' = ps !! (p - 1) in
				if p' == 0
				then putStrLn "Just a legend"
				else B.putStrLn $ B.take p' s

{-# LANGUAGE BangPatterns #-}
{-# OPTIONS_GHC -O3 -optc-O3 #-}
import Data.Word

import qualified Data.ByteString as B

data Item = Item { next :: Item, prefix :: Item, ch :: Word8, k :: Int } | NilItem deriving (Eq)

find i c =
	let i' = prefix i in
	if i' == NilItem
	then i
	else if ch i == c
		then i
		else find i' c

build :: Int -> Item -> B.ByteString -> [Item]
-- build ind i [] = []
build ind !i s =
	if s == B.empty then [] else
	let	i' = find i (B.head s)
		i'' = if ind /= 1 && ch i' == B.head s then next i' else i'
		is = build (ind + 1) i'' (B.tail s)
	in Item (head is) i'' (B.head $ B.tail s) ind : is

main = do
	s1 <- B.getLine

	let	s = B.init s1

	let	i = Item (head is) NilItem (B.head s) 0
		is = build 1 i s
		ps = map (\i -> k $ prefix i) is

		n = B.length s

		p = ps !! (n-1)

	if p == 0
	then putStrLn "Just a legend"
	else
		let ps' = filter (== p) (init ps) in
			if ps' /= []
			then B.putStrLn $ B.take (head ps') s
			else
				let p' = ps !! (p - 1) in
				if p' == 0
				then putStrLn "Just a legend"
				else B.putStrLn $ B.take p' s

{-# LANGUAGE BangPatterns #-}
{-# OPTIONS_GHC -O3 -optc-O3 #-}
data Item = Item { next :: Item, prefix :: Item, ch :: Char, k :: Int } | NilItem deriving (Eq)

find i c =
	let i' = prefix i in
	if i' == NilItem
	then i
	else if ch i == c
		then i
		else find i' c

build ind i "" = []
build ind !i !s =
	let	i' = find i (head s)
		i'' = if ind /= 1 && ch i' == head s then next i' else i'
		is = build (ind + 1) i'' (tail s)
	in Item (head is) i'' (head $ tail s) ind : is

main = do
	s <- getLine

	let	i = Item (head is) NilItem (head s) 0
		is = build 1 i s
		ps = map (\i -> k $ prefix i) is

		n = length s

		p = ps !! (n-1)

	if p == 0
	then putStrLn "Just a legend"
	else
		let ps' = filter (== p) (init ps) in
			if ps' /= []
			then putStrLn $ take (head ps') s
			else
				let p' = ps !! (p - 1) in
				if p' == 0
				then putStrLn "Just a legend"
				else putStrLn $ take p' s

{-# LANGUAGE BangPatterns #-}
{-# OPTIONS_GHC -O3 -optc-O3 #-}
import Data.Word

import qualified Data.ByteString as B

data Item = Item { next :: Item, prefix :: Item, ch :: Word8, k :: Int } | NilItem deriving (Eq)

build ind !i s
	| s == B.empty = []
	| otherwise =
		Item (head is) i'' (B.head $ B.tail s) ind : is
		where
			c = B.head s
			i' = find i
			i'' = if ind /= 1 && ch i' == c then next i' else i'
			is = build (ind + 1) i'' (B.tail s)

			find !i
				| i' == NilItem || ch i == c = i
				| otherwise = find i'
				where i' = prefix i

main = do
	s1 <- B.getLine

	let	s = B.init s1

	let	i = Item (head is) NilItem (B.head s) 0
		is = build 1 i s
		ps = map (\i -> k $ prefix i) is

		n = B.length s

		p = ps !! (n-1)

	if p == 0
	then putStrLn "Just a legend"
	else
		let ps' = filter (== p) (init ps) in
			if ps' /= []
			then B.putStrLn $ B.take (head ps') s
			else
				let p' = ps !! (p - 1) in
				if p' == 0
				then putStrLn "Just a legend"
				else B.putStrLn $ B.take p' s

{-# LANGUAGE BangPatterns #-}
{-# OPTIONS_GHC -O3 -optc-O3 #-}
data Item = Item { next :: Item, prefix :: Item, ch :: Char, k :: Int } | NilItem deriving (Eq)

find i c =
	let i' = prefix i in
	if i' == NilItem
	then i
	else if ch i == c
		then i
		else find i' c

build ind i "" = []
build ind !i s =
	let	i' = find i (head s)
		i'' = if ind /= 1 && ch i' == head s then next i' else i'
		is = build (ind + 1) i'' (tail s)
	in Item (head is) i'' (head $ tail s) ind : is

main = do
	s <- getLine

	let	i = Item (head is) NilItem (head s) 0
		is = build 1 i s
		ps = map (\i -> k $ prefix i) is

		n = length s

		p = ps !! (n-1)

	if p == 0
	then putStrLn "Just a legend"
	else
		let ps' = filter (== p) (init ps) in
			if ps' /= []
			then putStrLn $ take (head ps') s
			else
				let p' = ps !! (p - 1) in
				if p' == 0
				then putStrLn "Just a legend"
				else putStrLn $ take p' s

import Control.Applicative ((<$>))
import Data.List (mapAccumL)
import Data.Array (Array, listArray, elems, (!))
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as C8

zfunc :: Eq a => [a] -> [Int]
zfunc a = elems out
    where
    n = length a :: Int
    mkArray :: [a] -> Array Int a
    mkArray = listArray (0, n - 1)

    arr = mkArray a
    out = mkArray . (n:) . snd $ mapAccumL loop (0, 0) [1..] :: Array Int Int

    loop :: (Int, Int) -> Int -> ((Int, Int), Int)
    loop (l, r) i
        | r < i + 1 = ((i, r'), r' - i)
        | i + out ! (i - l) < r = ((l, r), out ! (i - l))
        | otherwise = ((i, r''), r'' - i)
        where
        next = head . dropWhile (\j -> j < n && arr ! j == arr ! (j - i))
        [r', r''] = map next [[i..], [r..]] :: [Int]

solve :: String -> String
solve [_] = "Just a legend"
solve line = if len /= 0 then take len line else "Just a legend"
    where
    n = length line :: Int
    a = tail . zip [0..] . zfunc $ line :: [(Int, Int)]

    sub = maximum $ map f a :: Int -- longest *strict* substring
        where f (i, k) = if i + k == n then k - 1 else k

    len = maximum $ map f a :: Int
        where f (i, k) = if i + k /= n || sub < k then 0 else k

main = C8.pack . solve . C8.unpack . C8.init <$> B.getLine >>= C8.putStrLn

import Data.Maybe (fromMaybe, listToMaybe)

import Control.Monad (foldM_)
import Data.Array.MArray (newArray, readArray, writeArray)
import Data.Array.ST (runSTUArray)
import Data.Array.Unboxed -- (UArray, (!), listArray, elems)

(?) :: Bool -> a -> a -> a
(?) p a b  =  if p then a else b

zFunction :: String -> UArray Int Int
zFunction s  =  runSTUArray $ do
    z  <-  newArray (1, n) 0
    writeArray z 1 n
    foldM_ (iter z) (1, 1) [2..n]
    return z
  where
    n   =  length s
    s'  =  listArray (1, n) s :: UArray Int Char
    iter z (l, r) i  =  do
        zil  <-  readArray z (i - l + 1)
        let z0  =  (i > r) ? 0 $ min (r - i + 1) zil
        let zi  =  head $ dropWhile (\j -> i + j <= n && s' ! (j + 1) == s' ! (i + j)) [z0..]
        writeArray z i zi
        return $ (i + zi - 1 > r) ? (i, i + zi - 1) $ (l, r)

solve :: String -> Maybe String
solve s
  | n <= 2  =  Nothing
  | otherwise  =  listToMaybe [take (z ! i) s | i <- [2..n], (z ! i) <= mx, i + z ! i == n + 1]
  where
    n   =  length s
    z   =  zFunction s
    z'  =  zFunction $ init s
    mx  =  maximum $ tail $ elems z'

main :: IO ()
main  =  getLine >>= putStrLn . fromMaybe "Just a legend" . solve

{-# LANGUAGE BangPatterns #-}
{-# OPTIONS_GHC -O3 -optc-O3 #-}
import Data.Word

import qualified Data.ByteString as B

data Item = Item { next :: Item, prefix :: Item, ch :: Word8, k :: Int } | NilItem deriving (Eq)

find i c =
	let i' = prefix i in
	if i' == NilItem
	then i
	else if ch i == c
		then i
		else find i' c

build :: Int -> Item -> B.ByteString -> [Item]
-- build ind i [] = []
build ind !i s =
	if s == B.empty then [] else
	let	i' = find i (B.head s)
		i'' = if ind /= 1 && ch i' == B.head s then next i' else i'
		is = build (ind + 1) i'' (B.tail s)
	in Item (head is) i'' (B.head $ B.tail s) ind : is

main = do
	s <- B.getLine

	let	i = Item (head is) NilItem (B.head s) 0
		is = build 1 i s
		ps = map (\i -> k $ prefix i) is

		n = B.length s

		p = ps !! (n-1)

	if p == 0
	then putStrLn "Just a legend"
	else
		let ps' = filter (== p) (init ps) in
			if ps' /= []
			then B.putStrLn $ B.take (head ps') s
			else
				let p' = ps !! (p - 1) in
				if p' == 0
				then putStrLn "Just a legend"
				else B.putStrLn $ B.take p' s

{-# LANGUAGE BangPatterns, MagicHash #-}
{-# OPTIONS_GHC -O2 -optc-O2 -funbox-strict-fields #-}
import Data.Word

import qualified Data.ByteString as B

data Item = Item { next :: Item, prefix :: !Item, ch :: Word8, k :: !Int } | NilItem deriving (Eq)

find i c =
	let i' = prefix i in
	if i' == NilItem
	then i
	else if ch i == c
		then i
		else find i' c

build ind !i s =
	let	i' = find i (B.head s)
		i'' = if ind /= 1 && ch i' == B.head s then next i' else i'
		is = build (ind + 1) i'' (B.tail s)
	in Item (head is) i'' (B.head $ B.tail s) ind : is

main = do
	s1 <- B.getLine

	let	s = B.init s1

	let	i = Item (head is) NilItem (B.head s) 0
		is = build 1 i s
		ps = map (\i -> k $ prefix i) is

		n = B.length s

		p = ps !! (n-1)

	if p == 0
	then putStrLn "Just a legend"
	else
		let ps' = filter (== p) (init ps) in
			if ps' /= []
			then B.putStrLn $ B.take (head ps') s
			else
				let p' = ps !! (p - 1) in
				if p' == 0
				then putStrLn "Just a legend"
				else B.putStrLn $ B.take p' s

{-# LANGUAGE BangPatterns, MagicHash #-}
{-# OPTIONS_GHC -O2 -optc-O2 -funbox-strict-fields #-}
import Data.Word

import qualified Data.ByteString as B

data Item = Item { next :: Item, prefix :: Item, ch :: Word8, k :: Int } | NilItem deriving (Eq)

find i c =
	if i' == NilItem || ch i == c then i else find i' c
	where i' = prefix i

build ind !i s =
	Item (head is) i'' (B.head $ B.tail s) ind : is
	where
		i' = find i (B.head s)
		i'' = if ind /= 1 && ch i' == B.head s then next i' else i'
		is = build (ind + 1) i'' (B.tail s)

main = do
	s1 <- B.getLine

	let	s = B.init s1

	let	i = Item (head is) NilItem (B.head s) 0
		is = build 1 i s
		ps = map (\i -> k $ prefix i) is

		n = B.length s

		p = ps !! (n-1)

	if p == 0
	then putStrLn "Just a legend"
	else
		let ps' = filter (== p) (init ps) in
			if ps' /= []
			then B.putStrLn $ B.take (head ps') s
			else
				let p' = ps !! (p - 1) in
				if p' == 0
				then putStrLn "Just a legend"
				else B.putStrLn $ B.take p' s

import Control.Applicative ((<$>))
import Data.List (mapAccumL)
import Data.Array (Array, listArray, elems, (!))
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as C8

zfunc :: Eq a => [a] -> [Int]
zfunc a = elems out
    where
    n = length a :: Int
    mkArray :: [a] -> Array Int a
    mkArray = listArray (0, n - 1)

    arr = mkArray a
    out = mkArray . (n:) . snd $ mapAccumL loop (0, 0) [1..] :: Array Int Int

    loop :: (Int, Int) -> Int -> ((Int, Int), Int)
    loop (l, r) i
        | r < i + 1 = ((i, r'), r' - i)
        | i + out ! (i - l) < r = ((l, r), out ! (i - l))
        | otherwise = ((i, r''), r'' - i)
        where
        next = head . dropWhile (\j -> j < n && arr ! j == arr ! (j - i))
        [r', r''] = map next [[i..], [r..]] :: [Int]

solve :: String -> String
solve [_] = "Just a legend"
solve line = if len /= 0 then take len line else "Just a legend"
    where
    n = length line :: Int
    a = tail . zip [0..] . zfunc $ line :: [(Int, Int)]

    sub = maximum $ map f a :: Int -- longest *strict* substring
        where f (i, k) = if i + k == n then k - 1 else k

    len = maximum $ map f a :: Int
        where f (i, k) = if i + k /= n || sub < k then 0 else k

main = C8.pack . solve . C8.unpack <$> B.getLine >>= C8.putStrLn


import Control.Monad
import Data.List

main :: IO ()
main = do
  t <- readLn
  replicateM_ t $ do
    [a, b, c] <- map read . words <$> getLine
    putStrLn $ if solve a b c then "YES" else "NO"

solve :: Integer -> Integer -> Integer -> Bool
solve a b c =
  or
    [ let am = 2 * b - c in am > 0 && am `mod` a == 0,
      let bm2 = a + c in bm2 > 0 && bm2 `mod` (b * 2) == 0,
      let cm = 2 * b - a in cm > 0 && cm `mod` c == 0
    ]

-- c - b == b - a * m => a * m - 2 * b + c == 0
-- c - b * m = b * m - a => a - m * 2 * b + c == 0
-- c * m - b = b - a => a - 2 * b + c * m == 0

import Control.Monad

solve :: IO ()
solve = do
    ~[a, b, c] <- map read . words <$> getLine
    let a' = 2 * b - c
        c' = 2 * b - a
        b' = (c + a) `div` 2
        ok = a' > 0 && a' `mod` a == 0
          || c' > 0 && c' `mod` c == 0
          || even (c - a) && b' > 0 && b' `mod` b == 0
    putStrLn $ if ok then "YES" else "NO"

main :: IO ()
main = flip replicateM_ solve =<< readLn

import Data.Char ( isDigit )

main :: IO()
main = do
    tStr <- getLine
    let t = read tStr :: Int
    solve t

solve :: Int -> IO()
solve 0 = return ()
solve t = do

    inStr <- getLine
    let list = readIntList inStr

    let ans = if test list then "YES" else "NO"
    putStrLn ans
    solve (t - 1)

test :: [Int] -> Bool
test [a, b, c]
    | last `mod` c == 0  && last > 0 = True
    | first `mod` a == 0 && first > 0 = True
    | even (a + c) && divisible = True
    | otherwise = False
        where
            first = 2*b - c
            last = 2 * b - a
            divisible = (mid `mod` b) == 0
            mid = (a + c) `div` 2

test _ = False

prog :: [Int] -> Bool
prog [a, b, c]
    | 2 * b == a + c = True
    | otherwise = False
prog _ = False

readIntList :: String -> [Int]
readIntList [] = []
readIntList (h : t)
    | isDigit h = read (takeWhile isDigit (h : t)) : readIntList (dropWhile isDigit t)
    | otherwise = readIntList t

import Control.Monad(replicateM)
import qualified Data.ByteString.Lazy.Char8 as B
import qualified Data.ByteString.Builder.Prim as Prim
import Data.ByteString.Builder
import Control.Monad.Trans.State
import Data.Maybe
import System.IO

divides :: Int -> Int -> Bool
divides a b = b `rem` a == 0

canMakeAP :: Int -> Int -> Int -> Bool
canMakeAP a b c =
  (2*b - c > 0 && a `divides` (2*b - c)) ||
  (2*b) `divides` (c + a) ||
  (2*b - a > 0 && c `divides` (2*b - a))

solve :: SB Builder
solve = do
  ~[t] <- getInts 1
  fmap mconcat $ replicateM t $ do
    ~[a, b, c] <- getInts 3
    let ans = canMakeAP a b c
    return $ string7 (if ans then "YES\n" else "NO\n")

-- stdin/out from solution by clyring
type SB = State [B.ByteString]

getNext :: Int -> SB [B.ByteString]
getNext = state . splitAt

parseInt = fst . fromJust . B.readInt

getInts :: Int -> SB [Int]
getInts n = map parseInt <$> getNext n

main :: IO ()
main = do
  hSetBuffering stdout NoBuffering
  inp <- B.getContents
  let  out = evalState solve $ B.words inp
  B.putStr $ toLazyByteString out

import Control.Monad (replicateM_)

readInt :: IO Int
readInt = readLn

readIntArray :: IO [Int]
readIntArray = (map read . words) <$> getLine

main :: IO ()
main = readInt >>= \t -> replicateM_ t test

test :: IO ()
test = do
    [a, b, c] <- readIntArray
    putStrLn $ calc a b c

calc :: Int -> Int -> Int -> String
calc a b c
  | (2 * b - c >= 1 && mod (2 * b - c) a == 0)
  || (even (c - a) && mod (div (c + a) 2) b == 0)
  || (2 * b - a >= 1 && mod (2 * b - a) c == 0) = "YES"
  | otherwise = "NO"

-- https://codeforces.com/contest/1624/problem/B
import Control.Monad (replicateM_)

answer a b c
    | (2*b-c >= 1 && (2*b-c)`mod`a == 0)
    ||(even (c-a) && ((c+a)`div`2)`mod`b == 0)
    ||(2*b-a >= 1 && (2*b-a)`mod`c == 0) = "YES"
    | otherwise = "NO"

main = getLine >>= flip replicateM_ run . read
run = do
    [a, b, c] <- (read <$>) . words <$> getLine
    putStrLn $ answer a b c

chunksOf :: Int -> [a] -> [[a]]
chunksOf _ [] = []
chunksOf i xs = take i xs : chunksOf i (drop i xs)

toArr :: Read a => String -> [a]
toArr = map read . words

type InType  = (Int, Int, Int)
type OutType = Bool

solve :: InType -> OutType
solve (a, b, c) =
    let d1 = c - b
        d2 = b - a
        d3 = c - a
    in ((b - d1) `mod` a == 0 && b - d1 >= a) ||
       ((b + d2) `mod` c == 0 && b + d2 >= c) ||
       (even d3 && (a + d3 `div` 2) `mod` b == 0)

receive :: [String] -> InType
receive [s] = case toArr s of
                [a, b, c] -> (a, b, c)
                _         -> error "wrong input"
receive _ = error  "wrong input"

main :: IO ()
main = interact $ unlines . map (showB . solve . receive) . chunksOf 1 . tail . lines
  where showB True = "YES"
        showB False = "NO"

import qualified Data.ByteString.Lazy.Char8 as P
import Data.ByteString.Builder
import qualified Data.ByteString.Builder.Prim as Prim
import System.IO
import Control.Monad.Trans.State
import Data.Maybe

--import Data.ByteString.Builder.Extra (flush) -- for interactive problems
import Control.Monad
--import Data.List
--import Data.Array.Unboxed

mainFun :: SP Builder
mainFun = do
  ~[t] <- getInts 1
  fmap mconcat $ replicateM t $ do
    ~[a, b, c] <- getInts 3
    let
      a' = case  (2 * b - c) `quotRem` a  of
        (q, r) -> r == 0 && q > 0
      b' = (a + c) `rem` (2 * b) == 0
      c' = case  (2 * b - a) `quotRem` c  of
        (q, r) -> r == 0 && q > 0
    pure $ string7 $ if  a' || b' || c'
      then  "YES\n"
      else  "NO\n"

type SP = State [P.ByteString]

getNext :: Int -> SP [P.ByteString]
getNext = state . splitAt

getInts :: Int -> SP [Int]
getInts k = map (fst . fromJust . P.readInt) <$> getNext k

putInts :: [Int] -> Builder
putInts vs = let
  sepPrim = (,) ' ' Prim.>$<
    Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec
  in  case  vs  of
  [] -> char7 '\n'
  x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\n'

main :: IO ()
main = do
  hSetBuffering stdout NoBuffering
  inp <- P.getContents
  let  outp = evalState mainFun $ P.words inp
  P.putStr $ toLazyByteString outp

import Control.Monad

solve :: IO ()
solve = do
    ~[a, b, c] <- map read . words <$> getLine
    let a' = 2 * b - c
        c' = 2 * b - a
        b' = (c - a) `div` 2
        ok = a' > 0 && a' `mod` a == 0
          || c' > 0 && c' `mod` c == 0
          || even (c - a) && b' > 0 && b' `mod` b == 0
    putStrLn $ if ok then "YES" else "NO"

main :: IO ()
main = flip replicateM_ solve =<< readLn

import Control.Monad

solve :: IO ()
solve = do
    ~[a, b, c] <- map read . words <$> getLine
    let a' = 2 * b - c
        c' = 2 * b - a
        b' = (c - a) `div` 2
        ok = a' > 0 && a' `mod` a == 0
          || c' > 0 && c' `mod` c == 0
          || even (c - a) && b' `mod` b == 0
    putStrLn $ if ok then "YES" else "NO"

main :: IO ()
main = flip replicateM_ solve =<< readLn

import Data.Char ( isDigit )

main :: IO()
main = do
    tStr <- getLine
    let t = read tStr :: Int
    solve t

solve :: Int -> IO()
solve 0 = return ()
solve t = do

    inStr <- getLine
    let list = readIntList inStr

    let ans = if test list then "YES" else "NO"
    print ans
    solve (t - 1)

test :: [Int] -> Bool
test [a, b, c]
    | last `mod` c == 0  && last > 0 = True
    | first `mod` a == 0 && first > 0 = True
    | even (a + c) && divisible = True
    | otherwise = False
        where
            first = 2*b - c
            last = 2 * b - a
            divisible = (mid `mod` b) == 0
            mid = (a + c) `div` 2

test _ = False

prog :: [Int] -> Bool
prog [a, b, c]
    | 2 * b == a + c = True
    | otherwise = False
prog _ = False

readIntList :: String -> [Int]
readIntList [] = []
readIntList (h : t)
    | isDigit h = read (takeWhile isDigit (h : t)) : readIntList (dropWhile isDigit t)
    | otherwise = readIntList t


module Main where

import Control.Monad
import Control.Monad.ST
import Data.Array
import Data.Array.ST.Safe

char2Bool :: Char -> Bool
char2Bool '0' = False
char2Bool '1' = True

enumerate :: [a] -> [(Int, a)]
enumerate = zip [1 ..]

compressAdjMatrix :: [[Bool]] -> Array (Int, Int) Bool
compressAdjMatrix adjMatrix = array ((1, 1), (size, size)) indexedMatrix
    where size = length adjMatrix
          indexedMatrix = do
              (vert,  row) <- enumerate adjMatrix
              (neigh, adj) <- enumerate row
              return ((vert, neigh), adj)

runFloydWarshall :: Array (Int, Int) Bool -> Array (Int, Int) Int
runFloydWarshall adjMatrix = runST $ do
    -- prepare distances
    let (_, (size, _)) = bounds adjMatrix
    let range = [1 .. size]
    distances <- newArray ((1, 1), (size, size)) (size + 1) :: ST s (STUArray s (Int, Int) Int)
    forM_ [(i, j) | i <- range, j <- range] $ \(i, j) -> do
        when (adjMatrix ! (i, j)) $ writeArray distances (i, j) 1
        when (i == j)             $ writeArray distances (i, j) 0

    -- run main algo
    forM_ [(i, u, v) | i <- range, u <- range, v <- range] $ \(i, u, v) -> do
        duv <- readArray distances (u, v)
        dui <- readArray distances (u, i)
        div <- readArray distances (i, v)
        writeArray distances (u, v) $ min duv (dui + div)

    -- return the array
    freeze distances

compressPath :: [Int] -> Array (Int, Int) Int -> [Int]
compressPath path distances = reverse $ go path (tail path) [head path] (head path, 1)
    where go :: [Int] -> [Int] -> [Int] -> (Int,  Int) -> [Int]
          go    (u:_)    []       res      (_, _)       = u : res
          go    (u:us)   (v:vs)   res      (last, c)
            | distances ! (last, v) < c = go us vs (u : res) (u, 2)
            | otherwise                 = go us vs res       (last, succ c)

main :: IO ()
main = do
    size <- read <$> getLine
    matrix <- sequence $ replicate size $ map char2Bool <$> getLine
    pathLength <- (read :: String -> Int) <$> getLine
    path <- map read . words <$> getLine
    let distances = runFloydWarshall $ compressAdjMatrix matrix
        compressedPath = compressPath path distances
    print $ length compressedPath
    putStrLn $ unwords $ map show compressedPath

import Data.Char
import Data.Array.Unboxed
import Data.Array.ST.Safe
import Control.Monad
import Control.Monad.ST
import Data.Maybe
import Data.List

main = do
  n <- readLn
  adj <- listArray ((1,1),(n,n)) . map digitToInt . concat <$> replicateM n getLine :: IO (UArray (Int,Int) Int)
  k <- readLn :: IO Int
  ps <- map read . words <$> getLine :: IO [Int]
  let fw = runSTUArray $ do
        d <- thaw adj
        forM_ (indices adj) $ \p ->
          writeArray d p . (\e -> if e == 0 then 100^3 else 1) =<< readArray d p
        forM_ [1..n] $ \i ->
          forM_ [1..n] $ \j ->
            forM_ [1..n] $ \k -> do
              d0 <- readArray d (i,j)
              d1 <- liftM2 (+) (readArray d (i,k)) (readArray d (k,j))
              when (d1 < d0) $ writeArray d (i,j) d1
        return d
      s = solve fw (maximum (elems fw)) ps
  print (length s)
  putStrLn $ unwords $ map show s

solve fw up (first : ps) = first : go first ps where
  go _ [] = []
  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

{- This code was written by
Russell Emerine - linguist,
mathematician, coder,
musician, and metalhead. -}
import Data.Set as Set hiding (map)
import Data.Array.Unboxed as U hiding (map)
import Data.Array.IArray as I hiding (map)

distanceArray :: Array Int [Int] -> Array Int (UArray Int Int)
distanceArray g = I.listArray (1, n) [distances' a' | a' <- [1..n]] where
  n = snd $ bounds g
  distances' :: Int -> UArray Int Int
  distances' a = distances 0 (U.listArray (1, n) [-1 | _ <- [1..n]]) (Set.singleton a)
  distances :: Int -> UArray Int Int -> Set Int -> UArray Int Int
  distances _ result now | Set.null now = result
  distances d pre now = distances (d + 1) result next where
    result = pre // [(a, d) | a <- toList now, pre ! a == -1]
    next = Set.fromList [b | a <- Set.toList now, b <- g ! a, pre ! b == -1]

compress f (p:q:r:ps) = if f ! p ! q + f ! q ! r == f ! p ! r
  then compress f (p:r:ps)
  else p : compress f (q:r:ps)
compress _ ps = ps

makeGraph :: [[Char]] -> Array Int [Int]
makeGraph edges = listArray (1, n) [[j | (j, c) <- zip [1..n] es, c == '1'] | es <- edges] where
  n = length edges

main = do
  line1 <- getLine
  let n = read line1 :: Int
  contents <- getContents
  let
    (grid, query) = Prelude.splitAt n $ lines contents
    g = makeGraph grid
    ps = map read $ words $ head $ tail query
    a = distanceArray g
    result = compress a ps
  print $ length result
  putStrLn $ unwords $ map show result

{- This code was written by
Russell Emerine - linguist,
mathematician, coder,
musician, and metalhead. -}
import Data.Set as Set hiding (map)
import Data.Array.Unboxed as U hiding (map)
import Data.Array.IArray as I hiding (map)

distance :: Array Int [Int] -> Int -> Int -> Int
distance g a b = (I.listArray (1, n) [distances' a' | a' <- [1..n]] :: Array Int (UArray Int Int)) ! a ! b where
  n = snd $ bounds g
  distances' :: Int -> UArray Int Int
  distances' a = distances 0 (U.listArray (1, n) [-1 | _ <- [1..n]]) (Set.singleton a)
  distances :: Int -> UArray Int Int -> Set Int -> UArray Int Int
  distances _ result now | Set.null now = result
  distances d pre now = distances (d + 1) result next where
    result = pre // [(a, d) | a <- toList now]
    next = Set.fromList [b | a <- Set.toList now, b <- g ! a, pre ! b == -1]

compress g (p:q:r:ps) = if distance g p q + distance g q r == distance g p r
  then compress g (p:r:ps)
  else p : compress g (q:r:ps)
compress _ ps = ps

makeGraph :: [[Char]] -> Array Int [Int]
makeGraph edges = listArray (1, n) [[j | (j, c) <- zip [1..n] es, c == '1'] | es <- edges] where
  n = length edges

main = do
  line1 <- getLine
  let n = read line1 :: Int
  contents <- getContents
  let
    (grid, query) = Prelude.splitAt n $ lines contents
    g = makeGraph grid
    ps = map read $ words $ head $ tail query
    result = compress g ps
  print $ length result
  putStrLn $ unwords $ map show result

import Data.Char
import Data.Array.Unboxed
import Data.Array.ST.Safe
import Control.Monad
import Control.Monad.ST
import Data.Maybe
import Data.List

main = do
  n <- readLn
  adj <- listArray ((1,1),(n,n)) . map digitToInt . concat <$> replicateM n getLine :: IO (UArray (Int,Int) Int)
  k <- readLn :: IO Int
  ps <- map read . words <$> getLine :: IO [Int]
  let fw = runSTUArray $ do
        d <- thaw adj
        forM_ (indices adj) $ \p ->
          writeArray d p . (\e -> if e == 0 then 100^3 else 1) =<< readArray d p
        forM_ [1..n] $ \i ->
          forM_ [1..n] $ \j ->
            forM_ [1..n] $ \k -> do
              d0 <- readArray d (i,j)
              d1 <- liftM2 (+) (readArray d (i,k)) (readArray d (k,j))
              when (d1 < d0) $ writeArray d (i,j) d1
        return d
      s = solve fw (maximum (elems fw)) ps
  print (length s)
  putStrLn $ unwords $ map show s

solve fw up (first : ps) = first : go first ps where
  go _ [] = []
  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

import Data.Char
import Data.Array.Unboxed
import Data.Array.ST.Safe
import Control.Monad
import Control.Monad.ST
import Data.Maybe
import Data.List

main = do
  n <- readLn
  adj <- listArray ((1,1),(n,n)) . map digitToInt . concat <$> replicateM n getLine :: IO (UArray (Int,Int) Int)
  k <- readLn :: IO Int
  ps <- map read . words <$> getLine :: IO [Int]
  let fw = runSTUArray $ do
        d <- thaw adj
        forM_ (indices adj) $ \p ->
          writeArray d p . (\e -> if e == 0 then 100^3 else 1) =<< readArray d p
        forM_ [1..n] $ \i ->
          forM_ [1..n] $ \j ->
            forM_ [1..n] $ \k -> do
              d0 <- readArray d (i,j)
              d1 <- liftM2 (+) (readArray d (i,k)) (readArray d (k,j))
              when (d1 < d0) $ writeArray d (i,j) d1
        return d
  putStrLn $ unwords $ map show $ solve fw (maximum (elems fw)) ps

solve fw up (first : ps) = first : go first ps where
  go _ [] = []
  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


{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE InstanceSigs #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE UndecidableInstances #-}

import Data.Functor
import Data.Foldable
import Data.Traversable
import Data.Eq
import Data.Ord
import Data.Int
import Data.Bits
import Data.Char
import Data.List
import Data.IORef
import Data.Maybe
import Data.Ratio
import Data.Monoid
import Data.Either
import Data.String
import Data.Function
--import Data.Array
import Data.Array.ST
import Data.Array.Unboxed

import System.IO
import System.IO.Unsafe
import System.Exit
--import System.Random

import Control.Monad
import Control.Applicative
import Control.Arrow
import Control.Monad.Reader
import Control.Monad.Writer
import Control.Monad.Fail
import Control.Monad.State.Lazy
import Control.Monad.Except
import Control.Monad.Trans.Except
import Control.Monad.Identity
import Control.Monad.Except
import Control.Monad.Except

import qualified Data.ByteString.Char8 as C

readWhileNSpace :: IO String
readWhileNSpace = do
    c <- getChar
    if c == '\n' || c == ' ' then
        return ""
    else do
        cs <- readWhileNSpace
        return (c:cs)

readInt :: IO Int
readInt = read <$> readWhileNSpace

readArr :: Int -> IO a -> IO [a]
readArr n readF = replicateM n readF

maxInArr :: Ord a => [a] -> a
maxInArr = foldr1 max

il2 :: Int -> Int
il2 x = finiteBitSize x - 1 - countLeadingZeros x

data SparseTable = SparseTable { table :: UArray (Int, Int) Int, func :: Int -> Int -> Int }

buildSparse :: Array Int Int -> (Int -> Int -> Int) -> SparseTable
buildSparse e f = SparseTable (runSTUArray $ do
    let n = length e
    let lg = il2 n
    let pws = (listArray (0, lg - 1) $ take lg $ iterate (*2) 1) :: Array Int Int
    sp <- newArray ((0, 0), (lg, n)) 0
    forM_ [0..n - 1] $ \j -> do
        writeArray sp (0, j) (e ! j)
    forM_ [1..lg] $ \i ->
        let p = (pws!(i - 1)) in
        forM_ [0..(n - 2 * p)] $ \j -> do
            l <- readArray sp (i - 1, j)
            r <- readArray sp (i - 1, j + p)
            writeArray sp (i, j) $ f l r
    return sp) f

sparseQuery :: SparseTable -> Int -> Int -> Int
sparseQuery (SparseTable sp f) l r = let lg = il2 (r - l + 1); pws = iterate (*2) 1
    in f (sp!(lg, l)) (sp!(lg, r - (pws!!lg) + 1))

solve :: SparseTable -> SparseTable -> Array Int Int -> IO ()
solve spmin spmax pf = do
    ~[l, r] <- readInts
    let min' = (sparseQuery spmin (l-1) (r-1)) - (pf!(l-1))
    let max' = (sparseQuery spmax (l-1) (r-1)) - (pf!(l-1))
    putStrLn $ show $ if max' > 0 || (pf!r) - (pf!(l-1)) /= 0 then (-1) else (-min')

readInts :: IO [Int]
readInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine

main :: IO ()
main = do
    ~[n, q] <- readInts
    a <- readInts
    b <- readInts
    let delt = getZipList $ (-) <$> (ZipList a) <*> (ZipList b)
    let pf = scanl' (+) 0 delt
    let pf' = listArray (0, n) pf
    let spmin = buildSparse (listArray (0, n - 1) (drop 1 pf)) min
    let spmax = buildSparse (listArray (0, n - 1) (drop 1 pf)) max
    replicateM_ q $ solve spmin spmax pf'

{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE InstanceSigs #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE UndecidableInstances #-}

import Data.Functor
import Data.Foldable
import Data.Traversable
import Data.Eq
import Data.Ord
import Data.Int
import Data.Bits
import Data.Char
import Data.List
import Data.IORef
import Data.Maybe
import Data.Ratio
import Data.Monoid
import Data.Either
import Data.String
import Data.Function
--import Data.Array
import Data.Array.ST
import Data.Array.Unboxed

import System.IO
import System.IO.Unsafe
import System.Exit
--import System.Random

import Control.Monad
import Control.Applicative
import Control.Arrow
import Control.Monad.Reader
import Control.Monad.Writer
import Control.Monad.Fail
import Control.Monad.State.Lazy
import Control.Monad.Except
import Control.Monad.Trans.Except
import Control.Monad.Identity
import Control.Monad.Except
import Control.Monad.Except

import qualified Data.ByteString.Char8 as C

readWhileNSpace :: IO String
readWhileNSpace = do
    c <- getChar
    if c == '\n' || c == ' ' then
        return ""
    else do
        cs <- readWhileNSpace
        return (c:cs)

readInt :: IO Int
readInt = read <$> readWhileNSpace

readArr :: Int -> IO a -> IO [a]
readArr n readF = replicateM n readF

maxInArr :: Ord a => [a] -> a
maxInArr = foldr1 max

il2 :: Int -> Int
il2 x = finiteBitSize x - 1 - countLeadingZeros x

data SparseTable = SparseTable { table :: UArray (Int, Int) Int, func :: Int -> Int -> Int }

buildSparse :: Array Int Int -> (Int -> Int -> Int) -> SparseTable
buildSparse e f = SparseTable (runSTUArray $ do
    let n = length e
    let lg = il2 n
    let pws = take lg $ iterate (*2) 1
    sp <- newArray ((0, 0), (lg, n)) 0
    forM_ [0..n - 1] $ \j -> do
        writeArray sp (0, j) (e ! j)
    forM_ [1..lg] $ \i ->
        let p = (pws !! (i - 1)) in
        forM_ [0..(n - 2 * p)] $ \j -> do
            l <- readArray sp (i - 1, j)
            r <- readArray sp (i - 1, j + p)
            writeArray sp (i, j) $ f l r
    return sp) f

sparseQuery :: SparseTable -> Int -> Int -> Int
sparseQuery (SparseTable sp f) l r = let pws = iterate (*2) 1; lg = il2 (r - l + 1)
    in f (sp!(lg, l)) (sp!(lg, r - (pws !! lg) + 1))

solve :: SparseTable -> SparseTable -> Array Int Int -> IO ()
solve spmin spmax pf = do
    ~[l, r] <- readInts
    let min' = (sparseQuery spmin (l-1) (r-1)) - (pf!(l-1))
    let max' = (sparseQuery spmax (l-1) (r-1)) - (pf!(l-1))
    putStrLn $ show $ if max' > 0 || (pf!r) - (pf!(l-1)) /= 0 then (-1) else (-min')

readInts :: IO [Int]
readInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine

main :: IO ()
main = do
    ~[n, q] <- readInts
    a <- readInts
    b <- readInts
    let delt = getZipList $ (-) <$> (ZipList a) <*> (ZipList b)
    let pf = scanl' (+) 0 delt
    let pf' = listArray (0, n) pf
    let spmin = buildSparse (listArray (0, n - 1) (drop 1 pf)) min
    let spmax = buildSparse (listArray (0, n - 1) (drop 1 pf)) max
    replicateM_ q $ solve spmin spmax pf'

import qualified Data.ByteString.Lazy.Char8 as P
import qualified Data.ByteString.Builder as B
import Data.ByteString.Builder.Prim
import System.IO

import Control.Monad
import Control.Monad.Trans.State
import Control.Monad.Trans.Class
import Data.Functor.Identity
import Data.Semigroup

import Data.List
import Data.Array.Unboxed
import Data.Bits
import Data.Int

il2 :: Int -> Int
il2 x = finiteBitSize x - 1 - countLeadingZeros x

type Sparse = (Array Int (UArray Int Int64), Int64 -> Int64 -> Int64)

query :: Sparse -> Int -> Int -> Int64
query (arr, fun) i j = let
  rank = il2 (j - i)
  rarr = arr ! rank
  in  fun (rarr ! i) (rarr ! (j + 1 - 1 `shift` rank))

construct :: (Int64 -> Int64 -> Int64) -> UArray Int Int64 -> Sparse
construct fun initArr = let
  step :: UArray Int Int64 -> Int -> UArray Int Int64
  step arr w = let
    (p, q) = bounds arr
    nq = q - w
    in  listArray (p, nq)
        $ [fun (arr ! i) (arr ! (i + w)) | i <- [p..nq]]
  (ip, iq) = bounds initArr
  lastLayer = il2 (iq - ip)
  ws = take lastLayer $ iterate (* 2) 1 -- this is why you should use pre-written code
  in  (listArray (0, lastLayer) $ scanl step initArr ws, fun)

main :: IO ()
main = (P.words <$> P.getContents >>=) $ evalStateT $ do
  [n,q] <- getInts 2
  a <- getInts n
  b <- getInts n
  let
    diffs = zipWith (-) b a
    psums = listArray (0, n) $ scanl' (\x y -> x + fromIntegral y) 0 diffs
    possible = construct min psums
    cost = construct max psums
    solve :: Int -> Int -> Maybe Int64
    solve li ri = do
      guard $ psums ! (li - 1) == psums ! ri
      guard $ query possible li ri >= psums ! ri
      pure $ query cost li ri - psums ! ri
  replicateM_ q $ do
    [li, ri] <- getInts 2
    putInt64s $ pure $ case  solve li ri  of
      Nothing -> 0-1
      Just k -> k

type SP = StateT [P.ByteString]
type SIO = SP IO

liftPure :: Monad m => SP Identity t -> SP m t
liftPure = mapStateT (pure . runIdentity)

getNext :: Monad m => Int -> SP m [P.ByteString]
getNext = state . splitAt

getInts :: Monad m => Int -> SP m [Int]
getInts k = do
  vs <- getNext k
  pure [v | Just (v, _) <- map P.readInt vs]

putInt64s :: [Int64] -> SIO ()
putInt64s vs = let
  sepPrim = (,) ' ' >$< liftFixedToBounded char7 >*< int64Dec
  in  lift $ B.hPutBuilder stdout $ case  vs  of
  [] -> B.char7 '\n'
  x : xs -> B.int64Dec x <> primMapListBounded sepPrim xs <> B.char7 '\n'

import qualified Data.ByteString.Lazy.Char8 as P
import qualified Data.ByteString.Builder as B
import Data.ByteString.Builder.Prim
import System.IO

import Control.Monad
import Control.Monad.Trans.State
import Control.Monad.Trans.Class
import Data.Functor.Identity
import Data.Semigroup

import Data.List
import Data.Array.Unboxed
import Data.Bits
import Data.Int

il2 :: Int -> Int
il2 x = finiteBitSize x - 1 - countLeadingZeros x

type Sparse = (Array Int (UArray Int Int64), Int64 -> Int64 -> Int64)

query :: Sparse -> Int -> Int -> Int64
query (arr, fun) i j = let
  rank = il2 (j - i)
  rarr = arr ! rank
  in  fun (rarr ! i) (rarr ! (j + 1 - 1 `shift` rank))

construct :: (Int64 -> Int64 -> Int64) -> UArray Int Int64 -> Sparse
construct fun initArr = let
  step :: UArray Int Int64 -> Int -> UArray Int Int64
  step arr w = let
    (p, q) = bounds arr
    nq = q - w
    in  listArray (p, nq)
        $ [fun (arr ! i) (arr ! (i + w)) | i <- [p..nq]]
  (ip, iq) = bounds initArr
  lastLayer = il2 (iq - ip)
  in  (listArray (0, lastLayer) $ scanl step initArr [1..lastLayer], fun)

main :: IO ()
main = (P.words <$> P.getContents >>=) $ evalStateT $ do
  [n,q] <- getInts 2
  a <- getInts n
  b <- getInts n
  let
    diffs = zipWith (-) b a
    psums = listArray (0, n) $ scanl' (\x y -> x + fromIntegral y) 0 diffs
    possible = construct min psums
    cost = construct max psums
    solve :: Int -> Int -> Maybe Int64
    solve li ri = do
      guard $ psums ! (li - 1) == psums ! ri
      guard $ query possible li ri >= psums ! ri
      pure $ query cost li ri - psums ! ri
  replicateM_ q $ do
    [li, ri] <- getInts 2
    putInt64s $ pure $ case  solve li ri  of
      Nothing -> 0-1
      Just k -> k

type SP = StateT [P.ByteString]
type SIO = SP IO

liftPure :: Monad m => SP Identity t -> SP m t
liftPure = mapStateT (pure . runIdentity)

getNext :: Monad m => Int -> SP m [P.ByteString]
getNext = state . splitAt

getInts :: Monad m => Int -> SP m [Int]
getInts k = do
  vs <- getNext k
  pure [v | Just (v, _) <- map P.readInt vs]

putInt64s :: [Int64] -> SIO ()
putInt64s vs = let
  sepPrim = (,) ' ' >$< liftFixedToBounded char7 >*< int64Dec
  in  lift $ B.hPutBuilder stdout $ case  vs  of
  [] -> B.char7 '\n'
  x : xs -> B.int64Dec x <> primMapListBounded sepPrim xs <> B.char7 '\n'

import qualified Data.ByteString.Lazy.Char8 as P
import qualified Data.ByteString.Builder as B
import Data.ByteString.Builder.Prim
import System.IO

import Control.Monad
import Control.Monad.Trans.State
import Control.Monad.Trans.Class
import Data.Functor.Identity
import Data.Semigroup

import Data.List
import Data.Array.Unboxed
import Data.Bits
import Data.Int

il2 :: Int -> Int
il2 x = finiteBitSize x - 1 - countLeadingZeros x

type Sparse = (Array Int (UArray Int Int64), Int64 -> Int64 -> Int64)

query :: Sparse -> Int -> Int -> Int64
query (arr, fun) i j = let
  rank = il2 (j - i)
  rarr = arr ! rank
  in  fun (rarr ! i) (rarr ! (j - 1 `shift` rank))

construct :: (Int64 -> Int64 -> Int64) -> UArray Int Int64 -> Sparse
construct fun initArr = let
  step :: UArray Int Int64 -> Int -> UArray Int Int64
  step arr w = let
    (p, q) = bounds arr
    nq = q - w
    in  listArray (p, nq)
        $ [fun (arr ! i) (arr ! (i + w)) | i <- [p..nq]]
  (ip, iq) = bounds initArr
  lastLayer = il2 (iq - ip)
  in  (listArray (0, lastLayer) $ scanl step initArr [1..lastLayer], fun)

main :: IO ()
main = (P.words <$> P.getContents >>=) $ evalStateT $ do
  [n,q] <- getInts 2
  a <- getInts n
  b <- getInts n
  let
    diffs = zipWith (-) b a
    psums = listArray (0, n) $ scanl' (\x y -> x + fromIntegral y) 0 diffs
    possible = construct min psums
    cost = construct max psums
    solve :: Int -> Int -> Maybe Int64
    solve li ri = do
      guard $ psums ! (li - 1) == psums ! ri
      guard $ query possible li ri >= psums ! ri
      pure $ query cost li ri - psums ! ri
  replicateM_ q $ do
    [li, ri] <- getInts 2
    putInt64s $ pure $ case  solve li ri  of
      Nothing -> 0-1
      Just k -> k

type SP = StateT [P.ByteString]
type SIO = SP IO

liftPure :: Monad m => SP Identity t -> SP m t
liftPure = mapStateT (pure . runIdentity)

getNext :: Monad m => Int -> SP m [P.ByteString]
getNext = state . splitAt

getInts :: Monad m => Int -> SP m [Int]
getInts k = do
  vs <- getNext k
  pure [v | Just (v, _) <- map P.readInt vs]

putInt64s :: [Int64] -> SIO ()
putInt64s vs = let
  sepPrim = (,) ' ' >$< liftFixedToBounded char7 >*< int64Dec
  in  lift $ B.hPutBuilder stdout $ case  vs  of
  [] -> B.char7 '\n'
  x : xs -> B.int64Dec x <> primMapListBounded sepPrim xs <> B.char7 '\n'

import qualified Data.ByteString.Lazy.Char8 as P
import qualified Data.ByteString.Builder as B
import Data.ByteString.Builder.Prim
import System.IO

import Control.Monad
import Control.Monad.Trans.State
import Control.Monad.Trans.Class
import Data.Functor.Identity
import Data.Semigroup

import Data.List
import Data.Array.Unboxed
import Data.Bits

il2 :: Int -> Int
il2 x = finiteBitSize x - 1 - countLeadingZeros x

type Sparse = (Array Int (UArray Int Int), Int -> Int -> Int)

query :: Sparse -> Int -> Int -> Int
query (arr, fun) i j = let
  rank = il2 (j - i)
  rarr = arr ! rank
  in  fun (rarr ! i) (rarr ! (j - 1 `shift` rank))

construct :: (Int -> Int -> Int) -> UArray Int Int -> Sparse
construct fun initArr = let
  step :: UArray Int Int -> Int -> UArray Int Int
  step arr w = let
    (p, q) = bounds arr
    nq = q - w
    in  listArray (p, nq)
        $ [fun (arr ! i) (arr ! (i + w)) | i <- [p..nq]]
  (ip, iq) = bounds initArr
  lastLayer = il2 (iq - ip)
  in  (listArray (0, lastLayer) $ scanl step initArr [1..lastLayer], fun)

main :: IO ()
main = (P.words <$> P.getContents >>=) $ evalStateT $ do
  [n,q] <- getInts 2
  a <- getInts n
  b <- getInts n
  let
    psums = listArray (0, n) $ scanl' (+) 0 $ zipWith (-) b a
    possible = construct min psums
    cost = construct max psums
    solve :: Int -> Int -> Maybe Int
    solve li ri = do
      guard $ psums ! (li - 1) == psums ! ri
      guard $ query possible li ri >= psums ! ri
      pure $ query cost li ri - psums ! ri
  replicateM_ q $ do
    [li, ri] <- getInts 2
    putInts $ pure $ case  solve li ri  of
      Nothing -> 0-1
      Just k -> k

type SP = StateT [P.ByteString]
type SIO = SP IO

liftPure :: Monad m => SP Identity t -> SP m t
liftPure = mapStateT (pure . runIdentity)

getNext :: Monad m => Int -> SP m [P.ByteString]
getNext = state . splitAt

getInts :: Monad m => Int -> SP m [Int]
getInts k = do
  vs <- getNext k
  pure [v | Just (v, _) <- map P.readInt vs]

putInts :: [Int] -> SIO ()
putInts vs = let
  sepPrim = (,) ' ' >$< liftFixedToBounded char7 >*< intDec
  in  lift $ B.hPutBuilder stdout $ case  vs  of
  [] -> B.char7 '\n'
  x : xs -> B.intDec x <> primMapListBounded sepPrim xs <> B.char7 '\n'


{-# LANGUAGE ForeignFunctionInterface #-}

import qualified Data.ByteString.Lazy.Char8 as LB
import qualified Data.ByteString as SB
import Data.ByteString.Internal (inlinePerformIO)
import Foreign.C.String (CString)
import Foreign.C (CDouble)
import Data.Maybe
import Data.List (sort, maximumBy, minimum, foldl')
import Data.Array
import qualified Data.Map as M
import qualified Data.IntMap as IM
import Debug.Trace

foreign import ccall unsafe "stdlib.h atof" c_atof :: CString -> IO Double
unsafeReadDouble = inlinePerformIO . flip SB.useAsCString c_atof
{-# INLINE unsafeReadDouble #-}
readDouble = unsafeReadDouble . SB.concat . LB.toChunks
readInt = fst . fromJust . LB.readInt

debug :: Show a => a -> b -> b
debug = trace . show
--debug _ = id

main = readFile "input.txt" >>= (writeFile "output.txt" . show . solve . parse . lines)

parse :: [String] -> (Int, [Int])
parse [nx, s] =
  let [n, x] = map read . words $ nx
      c = map read . words $ s
  in (x, c)

solve (x, c) =
  let n = length c
      v = takeWhile (<= x) $ scanl (+) 0 $ sort [(n - i) * (c !! i) | i <- [0..n - 1]]
  in length v - 1

import IO
import List

main = do
	i <- openFile "input.txt" ReadMode
	o <- openFile "output.txt" WriteMode
	c <- hGetContents i
	hPutStr o $ show $ gao $ map read $ words c
	hClose o

gao (n:x:c) = length $ takeWhile (<=x) $ scanl1 (+) $ sort $ zipWith (*) [1 ..] $ reverse c


{-# OPTIONS_GHC -O2 #-}
{-# LANGUAGE TypeApplications #-}

module Main ( main ) where

import qualified Data.ByteString.Char8 as BS
import Data.Array.Unboxed
import Data.List
import Data.Char ( isSpace )

main :: IO ()
main = do
  [n, k] <- line
  a <- arr (n - 1) <$> line
  let
    medianIsGE m = any (\i -> psums ! i - pmins ! (i - k) > 0) [k..n]
      where
        psums = arr n $ scanl' (+) 0 $ (\e -> if e < m then -1 else 1 :: Int) <$> elems a
        pmins = arr n $ scanl' min 0 $ tail $ elems psums
  print $ upperBound medianIsGE 1 n

arr :: Int -> [Int] -> UArray Int Int
arr n = listArray @UArray (0 :: Int, n)

upperBound :: Integral a => (a -> Bool) -> a -> a -> a
upperBound f = go
  where
    go lo hi
      | hi - lo <= 1 = if f hi then hi else lo
      | otherwise    = if f mi then go mi hi else go lo mi
      where
        mi = (lo + hi) `div` 2

line :: IO [Int]
line = parseBS <$> BS.getLine

parseBS :: BS.ByteString -> [Int]
parseBS = go
  where
    go b = case BS.readInt b of
      Just (n, r) -> n:go (BS.dropWhile isSpace r)
      Nothing     -> []

import qualified Data.ByteString.Lazy.Char8 as P
import qualified Data.ByteString.Builder as B
import System.IO

import Control.Monad.Trans.State
import Control.Monad.Trans.Class
import Data.List hiding (insert)
import Data.Semigroup

-- length at least k, not length exactly k

import Data.Array.Unboxed

longestMedian :: [Int] -> Int -> Int -> Int
longestMedian a n x = let
  -- O(n)
  -- length of the longest segment with median at least x
  vals = scanl (\ct y -> ct + if  y >= x  then  1  else  0-1) 0 a
  firstVisits :: UArray Int Int
  lastVisits :: UArray Int Int
  firstVisits = accumArray min maxBound (0-n, n) $ zip vals [0..]
  lastVisits  = accumArray max minBound (0-n, n) $ zip vals [0..]
  prevs = scanl min maxBound $ elems firstVisits
  in  foldl' max 0 $ zipWith (-) (elems lastVisits) prevs

main :: IO ()
main = (P.getContents >>=) . evalStateT $ do
  [n, k] <- readInts
  a <- readInts
  let
    go li ri = if  li == ri
      then  li
      else  let
      mi = div (li + ri) 2
      in  if  longestMedian a n mi >= k
      then  go (mi + 1) ri
      else  go li mi
  putInts [go 1 (n+1) - 1]

type SIO = StateT P.ByteString IO

readLine :: SIO P.ByteString
readLine = do
  (out, next) <- P.break (<= '\r') <$> get
  put $ P.dropWhile (<= '\r') next
  pure out

readInts :: SIO [Int]
readInts = do
  currLine <- readLine
  pure [x | Just (x, _) <- P.readInt <$> P.words currLine]

putInts :: [Int] -> SIO ()
putInts li = let
  outBuilder = foldr (<>) (B.char7 '\n')
    $ intersperse (B.char7 ' ') (map B.intDec li)
  in  lift $ B.hPutBuilder stdout outBuilder

{-# OPTIONS_GHC -O2 #-}
{-# LANGUAGE TypeApplications #-}

module Main ( main ) where

import qualified Data.ByteString.Char8 as BS
import Data.Array.Unboxed
import Data.List
import Data.Char ( isSpace )

main :: IO ()
main = do
  [n, k] <- line
  a <- arr (n - 1) <$> line
  let
    medianIsGE m = any (\i -> psums ! i - pmins ! (i - k) > 0) [k..n]
      where
        psums = arr n $ scanl' (+) 0 $ (\e -> if e < m then -1 else 1 :: Int) <$> elems a
        pmins = arr n $ scanl' min 0 $ elems psums
  print $ upperBound medianIsGE 1 n

arr :: Int -> [Int] -> UArray Int Int
arr n = listArray @UArray (0 :: Int, n)

upperBound :: Integral a => (a -> Bool) -> a -> a -> a
upperBound f = go
  where
    go lo hi
      | hi - lo <= 1 = if f hi then hi else lo
      | otherwise    = if f mi then go mi hi else go lo mi
      where
        mi = (lo + hi) `div` 2

line :: IO [Int]
line = parseBS <$> BS.getLine

parseBS :: BS.ByteString -> [Int]
parseBS = go
  where
    go b = case BS.readInt b of
      Just (n, r) -> n:go (BS.dropWhile isSpace r)
      Nothing     -> []

{-# OPTIONS_GHC -O2 #-}
{-# LANGUAGE TypeApplications #-}

module Main ( main ) where

import qualified Data.ByteString.Char8 as BS
import Data.Array.Unboxed
import Data.List
import Data.Char ( isSpace )

main :: IO ()
main = do
  [n, k] <- line
  a <- arr (n - 1) <$> line
  let
    medianIsGE m = any (\i -> psums ! i - pmins ! (i - k) > 0) [k..n]
      where
        psums = arr n $ scanl' (+) 0 $ (\e -> if e < m then -1 else 1 :: Int) <$> elems a
        pmins = arr n $ scanl' min 0 $ elems psums
  print $ upperBound medianIsGE 1 n

arr :: Int -> [Int] -> UArray Int Int
arr n = listArray @UArray (0 :: Int, n)

upperBound :: Integral a => (a -> Bool) -> a -> a -> a
upperBound f = go
  where
    go lo hi
      | hi - lo <= 1 = lo
      | otherwise    = if f mi then go mi hi else go lo mi
      where
        mi = (lo + hi) `div` 2

line :: IO [Int]
line = parseBS <$> BS.getLine

parseBS :: BS.ByteString -> [Int]
parseBS = go
  where
    go b = case BS.readInt b of
      Just (n, r) -> n:go (BS.dropWhile isSpace r)
      Nothing     -> []

import qualified Data.ByteString.Lazy.Char8 as P
import qualified Data.ByteString.Builder as B
import System.IO

import Control.Monad.Trans.State
import Control.Monad.Trans.Class
import Data.List hiding (insert)
import Data.Semigroup

import qualified Data.IntMap.Strict as M

data Split = Split
  { smallVals :: !(M.IntMap Int)
  , largeVals :: !(M.IntMap Int)
  , imbalance :: !Int
  } deriving (Eq, Show)

getMedian :: Split -> Int
getMedian s = case  M.maxViewWithKey $ smallVals s  of
  Nothing           -> maxBound
  Just ((v, _), _)  -> v

empty :: Split
empty = Split M.empty M.empty 0

remOne :: Int -> Maybe Int
remOne x = if  x == 1
  then  Nothing
  else  Just (x-1)

correctBalance :: Split -> Split
correctBalance inp@(Split lv rv lean)
  | lean < -1 = let
      (toMove, _) = M.findMax lv
      newlv = M.updateMax remOne lv
      newrv = M.insertWith (+) toMove 1 rv
      in  Split newlv newrv $ lean + 2
  | lean > 0 = let
      (toMove, _) = M.findMin rv
      newlv = M.insertWith (+) toMove 1 lv
      newrv = M.updateMin remOne rv
      in  Split newlv newrv $ lean - 2
  | otherwise = inp

insert :: Int -> Split -> Split
insert x s@(Split lv rv lean) = correctBalance $ if  x <= getMedian s
  then  Split (M.insertWith (+) x 1 lv) rv (lean - 1)
  else  Split lv (M.insertWith (+) x 1 rv) (lean + 1)

remove :: Int -> Split -> Split
remove x s@(Split lv rv lean) = correctBalance $ if  x <= getMedian s
  then  Split (M.update remOne x lv) rv (lean + 1)
  else  Split lv (M.update remOne x rv) (lean - 1)

main :: IO ()
main = (P.getContents >>=) . evalStateT $ do
  [n, k] <- readInts
  a <- readInts
  let
    (sa, ta) = splitAt k a
    initSplit = foldl' (flip insert) empty sa
    update currSplit (new, old) = insert new $ remove old currSplit
    allSplits = scanl update initSplit $ zip ta a
  putInts [foldl' max minBound $ map getMedian allSplits]

type SIO = StateT P.ByteString IO

readLine :: SIO P.ByteString
readLine = do
  (out, next) <- P.break (<= '\r') <$> get
  put $ P.dropWhile (<= '\r') next
  pure out

readInts :: SIO [Int]
readInts = do
  currLine <- readLine
  pure [x | Just (x, _) <- P.readInt <$> P.words currLine]

putInts :: [Int] -> SIO ()
putInts li = let
  outBuilder = foldr (<>) (B.char7 '\n')
    $ intersperse (B.char7 ' ') (map B.intDec li)
  in  lift $ B.hPutBuilder stdout outBuilder


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

printS = do
    n <- readLn::IO Int
    xs <- readInts
    let nega = any (<0) xs
    if nega then putStrLn"no"
    else do putStrLn "YES"
            print $ maximum xs + 1
            putStrLn . unwords . map show $ [0..(maximum xs)]

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

import Control.Monad
import Data.Maybe
import Data.List
import qualified Data.ByteString.Char8 as C
import Data.ByteString.Builder
import System.IO

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

getInts :: IO [Int]
getInts = map parseInt . C.words <$> C.getLine

main :: IO ()
main = do
  [t] <- getInts
  output <- fmap mconcat $ replicateM t $ do
    [n] <- getInts
    as <- getInts
    let result = if any (<0) as
                   then string7 "NO"
                   else string7 "YES\n101\n" `mappend` (mconcat $ intersperse (charUtf8 ' ') $ map intDec [0..100])
    return $ result `mappend` charUtf8 '\n'
  hPutBuilder stdout output

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

printResult = do
    n <- readLn :: IO Int
    a <- readInts
    if length (filter (<0) a) > 0 then putStrLn "NO"
    else do
        putStrLn "YES"
        let m = maximum a
        print $ m + 1
        putStrLn . unwords . map show $ [0..m]

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

import Data.List (intercalate)
import Control.Monad (replicateM)

main = do t <- read <$> getLine
          replicateM t solve

solve = do getLine
           xs <- (map read . words) <$> getLine
           putStrLn (if any (< 0) xs then "nO" else ("yEs\n101\n" ++ intercalate " " (map show [0..100])))

makeInteger :: [String] -> [Int]
makeInteger = map read

main :: IO()
main = do
    line <- getLine
    let t = (read line::Int)
    solve t

solve :: Int -> IO()
solve 0 = return ()
solve t = do
    solve2
    solve (t - 1)

solve2 :: IO()
solve2 = do
    line <- getLine
    let n = (read line::Int)
    line <- getLine
    let inparr = words line
    let arr = makeInteger inparr
    let arr2 = [ if x < 0 then False else True | x <- arr ]
    let ck = elem False arr2
    if ck then do
        putStrLn "NO"
    else do
        putStrLn "YES"
        putStrLn "101"
        let arrprint = [show x | x <- [0..100]]
        let strprint = unwords arrprint
        putStrLn strprint

-- uninhm
-- https://codeforces.com/contest/1536/problem/A
-- greedy

import Control.Monad (replicateM_)

getInt = read <$> getLine
getInts = map read . words <$> getLine

solution = unlines [ "YES"
                   , "101"
                   , unwords (map show [0..100])
                   ]

main = do
  t <- getInt
  replicateM_ t $ do
    n <- getInt
    a <- getInts
    if any (< 0) a then
      putStrLn "NO"
    else
      putStr solution

-- uninhm
-- https://codeforces.com/contest/1536/problem/A
-- greedy

import Control.Monad (replicateM_)

getInt = read <$> getLine
getInts = map read . words <$> getLine

solution = unlines [ "YES"
                   , "101"
                   , unwords (map show [0..100])
                   ]

main = do
  t <- getInt
  replicateM_ t $ do
    n <- getInt
    a <- getInts
    if or [ i < 0 | i <- a ] then
      putStrLn "NO"
    else
      putStr solution

-- uninhm
-- https://codeforces.com/contest/1536/problem/A
-- greedy

import Control.Monad (replicateM_)

getInt = read <$> getLine
getInts = map read . words <$> getLine

solution = unlines [ "YES"
                   , "101"
                   , unwords (map show [0..100])
                   ]

main = do
  t <- getInt
  replicateM_ t $ do
    n <- getInt
    a <- getInts
    if or [ True | i <- a, i<0 ] then
      putStrLn "NO"
    else
      putStr solution

import Control.Monad (replicateM_)

getInt = read <$> getLine
getInts = map read . words <$> getLine

solution = "YES\n" ++ "101\n" ++ unwords (map show [0..100]) ++ "\n"

main = do
  t <- getInt
  replicateM_ t $ do
    n <- getInt
    a <- getInts
    if or [ True | i <- a, i<0 ] then
      putStrLn "NO"
    else
      putStr solution

module Main where

    solve :: IO ()
    solve = do
        getLine
        s <- getLine
        let a = map (\x -> read x :: Int) $ words s
            mn = minimum a
            mx = maximum a
        putStrLn $
            if mn < 0 then
                "NO"
            else
                "YES\n" ++ show(mx + 1) ++ "\n" ++
                    (concat $ map (\x -> show x ++ " ") [0..mx])

    iter :: Int -> IO ()
    iter 1 = solve
    iter n = do
        solve
        iter $ n - 1

    main :: IO ()
    main = do
        q <- getLine
        iter (read q :: Int)

module Main where

    solve :: IO ()
    solve = do
        getLine
        s <- getLine
        let a = map (\x -> read x :: Int) $ words s
            [mn, mx] = [minimum a, maximum a]
        putStrLn $
            if mn < 0 then
                "NO"
            else
                "YES\n" ++ show(mx + 1) ++ "\n" ++
                    (concat $ map (\x -> show x ++ " ") [0..mx])

    iter :: Int -> IO ()
    iter 1 = solve
    iter n = do
        solve
        iter $ n - 1

    main :: IO ()
    main = do
        q <- getLine
        iter (read q :: Int)

readSpaceLine :: Read (a) => IO [a]
readSpaceLine = do ln <- getLine
                   return . map read $ words ln

doTestCase ::  IO()
doTestCase = do _ <- getLine
                ns <- readSpaceLine :: IO [Int]
                if minimum ns < 0
                   then putStrLn "NO"
                   else let m = maximum ns
                            in do putStrLn "YES"
                                  print $ m + 1
                                  putStrLn . unwords . map show $ [0..maximum ns]

main = do t <- readLn :: IO Int
          sequence_ $ replicate t doTestCase

import Control.Monad
import Data.Maybe
import Data.List
import Text.Printf
import qualified Data.ByteString.Char8 as C

getInts :: IO [Int]
getInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine

main :: IO ()
main = do
    [caseNum] <- getInts
    forM_ [1..caseNum] $ \_ -> do
        [n] <- getInts
        arr <- getInts

        let areNeg = length ([x | x <- arr, x < 0]) > 0

        if areNeg then do
            printf("No\n")
        else do
            printf("Yes\n")
            let sol = [0..100]
            printf ("%d\n") (length sol)

            C.putStrLn $ C.pack $ unwords $ map show $ sol

{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE BinaryLiterals #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE NumDecimals #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TupleSections #-}

import Control.Applicative
import Control.Arrow
import Control.Monad
import Control.Monad.ST

import Data.Char
import Data.List
import Data.Maybe

import qualified Data.ByteString.Char8 as B

import Data.Array.ST.Safe
import Data.STRef

import Debug.Trace
import Text.Printf

readInt = readLn :: IO Int
readInteger = readLn :: IO Integer
readInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine
readIntegers = map ( fst . fromJust . B.readInteger ) . B.words <$> B.getLine

which a b f = if f then a else b
mp [ a, b ] = ( a, b )

modifyArray a i f = writeArray a i =<< f <$> readArray a i

printList [a] = print a
printList (a:as) = putStr ( show a ) >> putChar ' ' >> printList as

main = readInt >>= flip replicateM solve

solve = do
	getLine
	as <- readInts
	let
		g = foldl1 gcd as
		ma = maximum as
		res = takeWhile ( <= ma ) [ i * g | i <- [ 0 .. ] ]
	if minimum as < 0
		then putStrLn "No"
		else do
			putStrLn "Yes"
			print $ length res
			printList $ res

module Main where

    solve :: IO ()
    solve = do
        getLine
        s <- getLine
        let a = map (\x -> read x :: Int) $ words s
            [mn, mx] = [minimum a, maximum a]
        putStrLn $
            if mn < 0 then
                "NO"
            else
                "YES\n" ++ show(mx + 1) ++ "\n" ++
                    (concat $ map (\x -> show x ++ " ") [0..mx + 1])

    iter :: Int -> IO ()
    iter 1 = solve
    iter n = do
        solve
        iter $ n - 1

    main :: IO ()
    main = do
        q <- getLine
        iter (read q :: Int)

readSpaceLine :: Read (a) => IO [a]
readSpaceLine = do ln <- getLine
                   return . map read $ words ln

doTestCase ::  IO()
doTestCase = do _ <- getLine
                ns <- readSpaceLine :: IO [Int]
                if minimum ns < 0
                   then putStrLn "NO"
                   else let m = maximum ns
                            in do putStrLn "YES"
                                  print m
                                  putStrLn . unwords . map show $ [0..maximum ns]

main = do t <- readLn :: IO Int
          sequence_ $ replicate t doTestCase

readSpaceLine :: Read (a) => IO [a]
readSpaceLine = do ln <- getLine
                   return . map read $ words ln

doTestCase ::  IO()
doTestCase = do _ <- getLine
                ns <- readSpaceLine :: IO [Int]
                if minimum ns < 0
                   then putStrLn "NO"
                   else do putStrLn "YES"
                           putStrLn . unwords . map show $ [0..maximum ns]

main = do t <- readLn :: IO Int
          sequence_ $ replicate t doTestCase

import Control.Monad
import Data.Maybe
import Data.List
import Text.Printf
import qualified Data.ByteString.Char8 as C

getInts :: IO [Int]
getInts = map (fst . fromJust . C.readInt) . C.words <$> C.getLine

main :: IO ()
main = do
    [caseNum] <- getInts
    forM_ [1..caseNum] $ \_ -> do
        arr <- getInts

        let areNeg = length ([x | x <- arr, x < 0]) > 0

        if areNeg then do
            printf("No\n")
        else do
            printf("Yes\n")
            let sol = [0..100]
            printf ("%d\n") (length sol)

            C.putStrLn $ C.pack $ unwords $ map show $ sol

{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE BinaryLiterals #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE NumDecimals #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TupleSections #-}

import Control.Applicative
import Control.Arrow
import Control.Monad
import Control.Monad.ST

import Data.Char
import Data.List
import Data.Maybe

import qualified Data.ByteString.Char8 as B

import Data.Array.ST.Safe
import Data.STRef

import Debug.Trace
import Text.Printf

readInt = readLn :: IO Int
readInteger = readLn :: IO Integer
readInts = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine
readIntegers = map ( fst . fromJust . B.readInteger ) . B.words <$> B.getLine

which a b f = if f then a else b
mp [ a, b ] = ( a, b )

modifyArray a i f = writeArray a i =<< f <$> readArray a i

printList [a] = print a
printList (a:as) = putStr ( show a ) >> putChar ' ' >> printList as

main = readInt >>= flip replicateM solve

solve = do
	getLine
	as <- readInts
	let
		g = foldl1 gcd as
		ma = maximum as
		res = takeWhile ( <= ma ) [ i * g | i <- [ 0 .. ] ]
	if minimum as < 0
		then putStrLn "No"
		else do
			print $ length res
			printList $ res

import Control.Monad
import Data.Maybe
import Data.List
import qualified Data.ByteString.Char8 as C
import Data.ByteString.Builder
import System.IO

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

getInts :: IO [Int]
getInts = map parseInt . C.words <$> C.getLine

main :: IO ()
main = do
  [t] <- getInts
  output <- fmap mconcat $ replicateM t $ do
    [n] <- getInts
    as <- getInts
    let result = if any (<0) as
                   then string7 "NO"
                   else string7 "101\n" `mappend` (mconcat $ intersperse (charUtf8 ' ') $ map intDec [0..100])
    return $ result `mappend` charUtf8 '\n'
  hPutBuilder stdout output


import Control.Monad (liftM, replicateM)
import Data.Array ((!), listArray)
import Data.Char (ord, digitToInt)
import Data.List (intercalate, group, sort, unfoldr)

(?) :: Bool -> a -> a -> a
(?) p a b  =  if p then a else b

isPrime :: Integral a => a -> Bool
isPrime n  =  all (\x -> n `mod` x /= 0)
    $ takeWhile (\x -> x*x <= n) primes

primes :: Integral a => [a]
primes  =  2 : filter isPrime [3,5..]

factorization :: Integral a => a -> [(a, a)]
factorization 0  =  error "Don't factorization zero."
factorization 1  =  [(2,0)]
factorization n  =  f n primes
  where
    f 1 _  =  []
    f n (p:ps)
      | n `mod` p == 0  =  (p, a) : f m ps
      | p * p > n  =  [(n, 1)]
      | otherwise  =  f n ps
      where
        (m, a)  =  f' n 0
        f' n i
          | n `mod` p == 0  =  f' (n `div` p) (succ i)
          | otherwise  =  (n, i)

dividers :: Integral a => a -> [a]
dividers 0  =  error "Don't dividers zero."
dividers n  =  sort $ map (product . zipWith (^) ps) as
  where
    (ps, final)  =  unzip $ factorization n
    start  =  map (const 0) ps
    as  =  start : unfoldr next start
    next curr
      | curr == final  =  Nothing
      | otherwise  =  Just (a, a)
      where
        a  =  replicate i 0
            ++ [(curr !! i) + 1]
            ++ drop (i+1) curr
        i  =  length $ takeWhile (== 0) $ zipWith (-) final curr

solve :: Integer -> [Integer] -> Integer
solve 0 s  =  sum (map g z) - sum [f i * f j | i <- z, j <- z]
  where
    z  =  map (fromIntegral . length) $ filter ((== 0) . head) $ group s
    n  =  fromIntegral $ length s
    f n  =  n * (n+1) `div` 2
    g m  =  2 * f m * f n
solve k s  =  sum [countA i * countA (k `div` i) | i <- dividers k]
  where
    n  =  length s
    a  =  listArray (1, n) s
    zerosL  =  listArray (1, n) $ init
        $ scanl (\a b -> (b == 0) ? (a + 1) $ 0) 0 s
    zerosR  =  listArray (1, n) $ tail
        $ scanr (\a b -> (a == 0) ? (b + 1) $ 0) 0 s

    countA m  =  countA' m 1 1 (a ! 1)
    countA' m l r s
      | l > n  =  0
      | a ! l == 0  =  countA' m (l+1) r s
      | r < l  =  countA' m l (r+1) (s + a ! (r+1))
      | s == m  =  (1 + zerosL ! l) * (1 + zerosR ! r) + countA' m (l+1) r (s - a ! l)
      | s < m  =  if r == n then 0 else countA' m l (r+1) (s + a ! (r+1))
      | s > m  =  countA' m (l+1) r (s - a ! l)

main :: IO ()
main  =  do
    k  <-  readLn
    s  <-  liftM (map (fromIntegral . digitToInt)) getLine
    print $ solve k s

{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes,TupleSections #-}
import Control.Monad
import Control.Monad.ST
import Control.Applicative
import Control.Arrow
import Debug.Trace
import Text.Printf

import Data.List
import Data.Int
import Data.Bits
import Data.Char
import Data.Maybe
import Data.Array.Unboxed
import Data.Array.Base(unsafeAt)
import Data.Array.ST
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.ByteString.Char8 as B

readInt = B.readInt >>> fmap fst >>> fromMaybe 0
readInts = map readInt . B.words <$> B.getLine
readIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine
readLns :: Read a => IO [a]
readLns = map read . words <$> getLine
cmpFst (a,_) (b,_) = compare a b
cmpSnd (_,a) (_,b) = compare a b
cmpLen a b = length a `compare` length b
swap (a,b) = (b,a)
l2p (a:b:_) = (a,b)
p2l (a,b) = [a,b]
itof :: Int -> Double
itof = fromIntegral
defaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e
defaultArray = accumArray $ curry snd

main = do
    a <- readLn
    s <- map digitToInt <$> getLine
    print $ solve a s

solve :: Int -> [Int] -> Integer
solve a l | a == 0    = cast (count ! 0) * (cast (n * (n+1) - count ! 0))
          | otherwise = sum [ cast v * cast (count ! x)| (m,v) <- assocs count, m > 0, v > 0,
                  let (x,y) = divMod a m ,y == 0, x <= 4000*9]
    where
    n = length l
    s :: UArray Int Int
    s = listArray (0,n) (scanl (+) 0 l)
    as = [(unsafeAt s j - unsafeAt s (i-1),1) | i <- [1..n], j <- [i..n]]
    count :: UArray Int Int
    count = accumArray (+) 0 (0,4000*9) as
    cast = fromIntegral

{-
check = do
    a <- randomRIO (0,100)
    n <- return 2
    l <- replicateM n (randomRIO (1,9))
    print (a,n,l)
    print $ solve a l
    -}

{-# LANGUAGE BangPatterns #-}
import Data.Char (ord)
import Data.Int (Int64)
import Data.List (tails)
import Control.Applicative ((<$>))
import Data.Array.Unboxed (UArray, accumArray, assocs, (!))

solve :: Int -> String -> Int64
solve acc str
    | acc == 0  = (n * (n + 1) - zero) * zero
    | otherwise = sum . map count . filter pred . tail . assocs $ cnt
    where
    n = fromIntegral $ length str :: Int64
    a = scanl (+) 0 $ map ((+ inc).ord) str :: [Int]
        where inc = - ord '0'

    b = concat . map chunk . tails $ a
        where
        chunk     [] = []
        chunk (x:xs) = map (+ (-x)) xs

    size = last a :: Int
    cnt = accumArray (+) 0 (0, size) . zip b $ repeat 1 :: UArray Int Int64

    zero = cnt ! 0

    pred (_, 0) = False
    pred (i, _) = acc `mod` i == 0

    count (i, j)
        | size < i' = 0
        | otherwise = j * cnt ! i'
        where i' = acc `div` i

main = do
    acc <- read <$> getLine
    str <- getLine
    print $ solve acc str


import Control.Arrow ((>>>))

main :: IO ()
main =
  interact $
  lines >>>
  drop 1 >>> map (words >>> map read) >>> process >>> map show >>> unlines

process :: [[Int]] -> [Int]
process [] = []
process ([_, k]:xs:xss) = solve k xs : process xss

solve :: Int -> [Int] -> Int
solve k xs = minimum [cost c xs | c <- [1 .. 100]]
  where
    cost c xs
      | null xs = 0
      | head xs == c = cost c (tail xs)
      | otherwise = 1 + cost c (drop k xs)

-- {-# LANGUAGE
--     BangPatterns
--   , BlockArguments
--   , DataKinds
--   , DeriveGeneric
--   , DerivingStrategies
--   , DerivingVia
--   , FlexibleContexts
--   , FlexibleInstances
--   , GADTs
--   , GeneralizedNewtypeDeriving
--   , KindSignatures
--   , LambdaCase
--   , MultiParamTypeClasses
--   , MultiWayIf
--   , NPlusKPatterns
--   , NegativeLiterals
--   , OverloadedLabels
--   , OverloadedStrings
--   , ParallelListComp
--   , PolyKinds
--   , RankNTypes
--   , ScopedTypeVariables
--   , StrictData
--   , TupleSections
--   , TypeApplications
--   , TypeFamilies
--   , TypeOperators
--   , UndecidableInstances
--   , ViewPatterns
--   #-}

module Main where

import           Control.Applicative
import           Control.Arrow
import           Control.Monad
import           Control.Monad.ST
import qualified Data.ByteString.Char8         as BS
import           Data.Char
import           Data.Foldable
import           Data.Functor
import           Data.Int
import           Data.List
import           Data.Maybe
import           Data.Monoid
import           Data.Ord
import           Data.Semigroup                 ( Max(..)
                                                , Min(..)
                                                , All(..)
                                                , Arg(..)
                                                )
import           Data.Ratio
-- import           Data.Vector.Unboxing.Mutable   ( Unboxable )
-- import qualified Data.Vector.Unboxing.Mutable  as V
-- import           System.IO
-- import           Data.Proxy
-- import           GHC.TypeLits
-- import           GHC.Generics                   ( Generic )
-- import           GHC.Exts
-- import           Control.Monad.Primitive        ( PrimMonad(PrimState) )
-- import           Control.Monad.Trans.Class      ( MonadTrans(lift) )

-- {-# ANN module ("Hlint: ignore Unused LANGUAGE pragma" :: String) #-}
-- {-# ANN module ("Hlint: ignore Reduce duplication" :: String) #-}

twice :: (a -> a -> b) -> a -> b
twice f x = f x x

both :: Arrow a => a b c -> a (b, b) (c, c)
both = twice (***)

readsLn :: Read a => IO [a]
readsLn = mapM readIO . words =<< getLine

getInt :: IO Int
getInt = fst . fromJust . BS.readInt <$> BS.getLine

getInts :: IO [Int]
getInts = map (fst . fromJust . BS.readInt) . BS.words <$> BS.getLine

getInteger :: IO Integer
getInteger = fst . fromJust . BS.readInteger <$> BS.getLine

getIntegers :: IO [Integer]
getIntegers = map (fst . fromJust . BS.readInteger) . BS.words <$> BS.getLine

main = do
  t <- getInt
  replicateM_ t $ do
    [n, k] <- getInts
    c      <- getInts
    print $ minimum [ solve col k 0 c 0 | col <- [1 .. 100] ]

solve _ _ _ [] ans = ans
solve col k 0 (c : cs) ans =
  if c == col then solve col k 0 cs ans else solve col k k (c : cs) (ans + 1)
solve col k t (_ : cs) ans = solve col k (t -1) cs ans

import Control.Monad
import Data.List

main = do
  cases <- read <$> getLine
  replicateM_ cases $ do
    [n, k] <- (map read . words) <$> getLine :: IO [Int]
    houses <- (map read . words) <$> getLine :: IO [Int]
    let colors = nub houses
    putStrLn $ show $ minimum $ map (daysToPaint k houses) colors

daysToPaint :: Int -> [Int] -> Int -> Int
daysToPaint k houses color = daysToPaint' houses color 0
  where
    daysToPaint' [] color counter = counter
    daysToPaint' (house:houses) color counter =
      if color == house
      then daysToPaint' houses color counter
      else daysToPaint' (drop (k-1) houses) color (counter + 1)

import Control.Arrow ((>>>))

main :: IO ()
main =
  interact $
  lines >>>
  drop 1 >>> map (words >>> map read) >>> process >>> map show >>> unlines

process :: [[Int]] -> [Int]
process [] = []
process ([_, k]:xs:xss) = solve k xs : process xss

solve :: Int -> [Int] -> Int
solve k xs = minimum [cost c xs | c <- [1 .. 100]]
  where
    cost _ [] = 0
    cost c (x:xs)
      | c == x = cost c xs
      | otherwise = 1 + cost c (drop k xs)

import Control.Monad
import Data.List
import qualified Data.Map.Strict as Map

precolored :: [(Int, Int)] -> Map.Map Int Int
precolored xs = undefined

main = do
  cases <- read <$> getLine
  replicateM_ cases $ do
    [n, k] <- (map read . words) <$> getLine :: IO [Int]
    colors <- (map read . words) <$> getLine :: IO [Int]
    --print $ map (\x -> (head x, div (length x) k)) (group colors)
    let precolored = Map.fromListWith (+) $ map (\x -> (head x, div (length x) k)) (group colors)
    let (dominantColor, dominantCount) = Map.foldrWithKey maxWithKey (0, 0) precolored
    let wrongGroup =  filter (/= [dominantColor]) $ groupBy (wrongColor dominantColor) colors
    let groupWork = sum $ map (\x -> ceiling $ (fromIntegral $ length x) / (fromIntegral k)) wrongGroup
    putStrLn $ show $ groupWork

wrongColor :: Int -> Int -> Int -> Bool
wrongColor correct a b = (a /= correct && b /= correct)

maxWithKey :: Int -> Int -> (Int, Int) -> (Int, Int)
maxWithKey key value (oldKey, oldValue) = if value > oldValue then (key, value) else (oldKey, oldValue)


import qualified Data.Char as DC

solve :: Int -> IO ()
solve _ = do
    n <- getLine
    s <- getLine
    let xs = map DC.digitToInt (init s)
        lstdig = DC.digitToInt (last s)
        ans = lstdig + sum [x + 1 | x <- xs, x /= 0]
    print(ans)
main = do
    tc <- getLine
    let testcase = read tc :: Int
    mapM_ solve [1..testcase]

import Control.Monad
import Data.List
import Data.Char (digitToInt)

calc :: [Int] -> Int
calc s =
  foldl (\acc (x,i) ->
           if x==0 then
             acc
           else if i==0 then
             acc+x
           else
             acc+x+1
           ) 0 $ zip s [0..]

main = do
  line <- getLine
  let t = read line :: Int
  forM_ [1..t] $ \_ -> do
    unused <- getLine
    line <- getLine
    print $ calc $ reverse $ map digitToInt line


{- written by MarekCerny.com -}
{-# LANGUAGE ViewPatterns, PatternSynonyms  #-}
{-# LANGUAGE TupleSections                  #-}
{-# LANGUAGE UnicodeSyntax                  #-}
{-# LANGUAGE LambdaCase, MultiWayIf         #-}
import Data.Tuple
import Data.Bits
import Data.Maybe
import Data.Function
import Data.List
import Control.Exception
import qualified Data.HashMap.Strict as M
import Data.Sequence (Seq, (|>), (<|), (><))
import qualified Data.Sequence as S

main = interact $ unlines . sol . (map read) . words

sol :: [Int] -> [String]
sol (_:xs) = wrap $ case soly (zip xs [2..]) 1 of
  Just _ -> "Yes"
  Nothing -> "No"

soly :: [(Int,Int)] -> Int -> Maybe Bool
soly ms t = case filter ((==t).fst) ms of
  [] -> Just True
  xs -> let ss = map ((soly ms).snd) xs
        in if (all isJust $ ss) && (3 <= (length $ filter ((==True).fromJust) ss))
            then Just False
            -- else Nothing
            else Nothing

--------------------------------------------------------------------------------
groupOn :: Int -> [a] -> [[a]]
groupOn _ [] = []
groupOn n xs = let (sts, nds) = splitAt n xs in sts : groupOn n nds

fromBool :: Num a => Bool -> a
fromBool b = if b then 1 else 0

allInt :: [String] -> [[Integer]]
allInt = map ((map read) . words)

swrt :: Ord a => (a, a) -> (a, a)
swrt (a, b) | compare b a == LT = (b, a) | otherwise = (a, b)

wrap :: a -> [a]
wrap x = [x]

toSnd :: a->b-> (a,b)
toSnd x y = (x,y)

toFst :: b->a-> (a,b)
toFst y x = (x,y)

addCnt :: [String] -> [String]
addCnt ls = (show $ length ls) : ls

toBitMap :: Int -> [(Int, Bool)]
toBitMap = toBitMap' 31
  where
    toBitMap' (-1) _ = []
    toBitMap' n v = (n, v .&. (1`shiftL`n) > 0) : toBitMap' (n-1) v
--------------------------------------------------------------------------------
pattern Empty   <- (S.viewl -> S.EmptyL)
pattern x :< xs <- (S.viewl -> x S.:< xs)
pattern xs :> x <- (S.viewr -> xs S.:> x)
--------------------------------------------------------------------------------

main = getContents >>= putStrLn . solve . map read . lines

solve (n:p') = if minimum lnum >= 3 then "Yes" else "No"
    where p = map pred p'
          leaf = filter (not . (`elem` p)) [1 .. n - 1]
          lp = [ p !! (x - 1) | x <- leaf]
          lnum = [ length $ filter (==x) lp | x <- p ]

import Data.List

main = getContents >>= putStrLn . solve . map read . lines

solve (n:p') = if minimum lnum >= 3 then "Yes" else "No"
    where p = map pred p'
          leaf = filter (not . (`elem` p)) [1 .. n - 1]
          lp = [ p !! (x - 1) | x <- leaf]
          lnum = [ length $ elemIndices x lp | x <- p ]

import Control.Applicative
import Data.Maybe
import Data.List
import qualified Data.Map as Map

updateIsLeaf :: Map.Map Int Bool -> [Int] -> Map.Map Int Bool
updateIsLeaf a [] = a
updateIsLeaf a (x:xs) = Map.insert x False a'
    where a' = updateIsLeaf a xs

updateParentChildCount :: Map.Map Int Int -> Map.Map Int Bool -> Int -> Int -> Map.Map Int Int
updateParentChildCount childCount isLeaf parent node
    | (Map.lookup node isLeaf) == Nothing = childCount
    | fromJust (Map.lookup node isLeaf) == False = childCount
    | otherwise = Map.insertWith (+) parent 1 childCount

getFromMap :: Int -> Map.Map Int Bool -> Bool
getFromMap v m
    | Map.lookup v m == Nothing = False
    | otherwise = fromJust $ Map.lookup v m

isGood :: Map.Map Int Bool -> Bool -> Int -> Int -> Bool
isGood leafMap acc key value
    | isLeaf == True = acc
    | isLeaf == False = acc && (value >= 3)
    where isLeaf = getFromMap key leafMap

main :: IO ()
main = do
    n <- (read :: String -> Int) <$> getLine
    parents <- mapM (\_ -> (read :: String -> Int) <$> getLine) [1..(n - 1)]
    let emptyMap = Map.fromList $ zip [1..n] $ repeat True
        isLeafMap = updateIsLeaf emptyMap parents
        zeroChildCount = Map.fromList $ zip [1..n] [0,0..]
        updatedChildCount = foldl' (\m (a, b) -> updateParentChildCount m isLeafMap a b) zeroChildCount $ zip parents [2..]
        isSpruce = Map.foldlWithKey' (isGood isLeafMap) True updatedChildCount
    -- putStrLn . show $ updatedChildCount
    putStrLn $ if isSpruce then "Yes" else "No"

import qualified Data.Map as M
import qualified Data.Set as S

run :: Int -> [Int] -> Bool
run n l = let mm = M.fromList $ zip [1..n] (repeat S.empty)
              edges = foldr (\(idx, parent) m -> M.adjust (S.insert idx) parent m) mm (zip [2..n] l)
              leaves = M.keysSet (M.filter S.null edges)
          in all ((<=) 3 . S.size . S.filter (`S.member` leaves))  . filter (not . S.null) . map snd . M.toList $ edges

main :: IO ()
main = do
    n:l <- (map read . words) `fmap` getContents :: IO [Int]
    let ret = run n l
    putStrLn $ if ret then "Yes" else "No"

import Data.List

main = getContents >>= print . solve . map read . lines

solve (n:p') = if minimum lnum >= 3 then "Yes" else "No"
    where p = map pred p'
          leaf = filter (not . (`elem` p)) [1 .. n - 1]
          lp = [ p !! (x - 1) | x <- leaf]
          lnum = [ length $ elemIndices x lp | x <- p ]

import Control.Applicative
import Data.Maybe
import Data.List
import qualified Data.Map as Map

updateIsLeaf :: Map.Map Int Bool -> [Int] -> Map.Map Int Bool
updateIsLeaf a [] = a
updateIsLeaf a (x:xs) = Map.insert x False a'
    where a' = updateIsLeaf a xs

updateParentChildCount :: Map.Map Int Int -> Map.Map Int Bool -> Int -> Int -> Map.Map Int Int
updateParentChildCount childCount isLeaf parent node
    | (Map.lookup node isLeaf) == Nothing = childCount
    | fromJust (Map.lookup node isLeaf) == False = childCount
    | otherwise = Map.insertWith (+) parent 1 childCount

main :: IO ()
main = do
    n <- (read :: String -> Int) <$> getLine
    parents <- mapM (\_ -> (read :: String -> Int) <$> getLine) [1..(n - 1)]
    let emptyMap = Map.fromList $ zip [1..n] $ repeat True
        isLeafMap = updateIsLeaf emptyMap parents
        zeroChildCount = Map.fromList $ zip [1..n] [0,0..]
        updatedChildCount = foldl' (\m (a, b) -> updateParentChildCount m isLeafMap a b) zeroChildCount $ zip parents [2..]
        isSpruce = Map.foldl' (\x v -> x && (v == 0 || v >= 3)) True updatedChildCount
    putStrLn $ if isSpruce then "Yes" else "No"