import IO

--------------------------------------------------------------------------------
{-
import HUnit

testEmpty :: Test
testEmpty  =  Test "TestEmpty" $
    assertEq [] (solve' 2 [])

testOnePeople :: Test
testOnePeople  =  TestList "TestOnePeople"
  [
    Test "TestOneFloor (1)" $ assertEq 0 (solve 2 (1,1,0)),
    Test "TestOneFloor (2)" $ assertEq 1 (solve 2 (1,1,1)),
    Test "TestOneFloor (3)" $ assertEq 999 (solve 2 (1,1,999)),
    Test "TestOneFloor (4)" $ assertEq 0 (solve 2 (2,2,0)),
    Test "TestUpFloor (1)" $ assertEq 1 (solve 2 (1,2,0)),
    Test "TestUpFloor (2)" $ assertEq 2 (solve 3 (2,3,0)),
    Test "TestUpFloor (3)" $ assertEq 3 (solve 2 (1,2,2)),
    Test "TestUpUpFloor" $ assertEq 2 (solve 3 (1,3,0)),
    Test "TestDownFloor (1)" $ assertEq 2 (solve 2 (2,1,0)),
    Test "TestDownFloor (2)" $ assertEq 10 (solve 10 (10,9,0)),
    Test "TestDownFloor (3)" $ assertEq 4 (solve 3 (2,1,0)),
    Test "TestDownDownFloor" $ assertEq 11 (solve 10 (10,8,0)),
    Test "TestToLastFloor" $ assertEq (10^8 - 1) (solve (10^8) (1,10^8,0)),
    Test "TestToFirstFloor (1)" $ assertEq (2 * 10^8 - 2) (solve (10^8) (10^8,1,0)),
    Test "TestToFirstFloor (2)" $ assertEq (2 * 10^8 - 2) (solve (10^8) (10^8,1,10^8-1)),
    Test "TestLatecomerUp" $ assertEq 3 (solve 2 (1,2,1)),
    Test "TestLatercomerDown" $ assertEq 4 (solve 2 (2,1,2)),
    Test "TestNotLatercomerDown" $ assertEq 4 (solve 3 (2,1,3)),
    Test "TestLongExpectationUp" $ assertEq (10^8 - 1 + 2 * 10^8 - 2) (solve (10^8) (1,10^8,1)),
    Test "TestDeepRecursiveUp" $ assertEq 100000001 (solve 2 (1,2,10^8)),
    Test "TestDeepRecursiveDown" $ assertEq 100000002 (solve 2 (2,1,10^8)),
    Test "TestLongExpectationDown" $ assertEq (2 * (2 * 10^8 - 2)) (solve (10^8) (10^8,1,10^8))
  ]

testInput :: Test
testInput  =  TestList "TestInput"
  [
    Test "1" $ assertEq [9, 1, 0, 7, 10, 7, 5]
        (solve' 4 [(2,4,3), (1,2,0), (2,2,0), (1,2,1), (4,3,5), (1,2,2), (4,2,0)]),
    Test "2" $ assertEq [12, 10, 10, 8, 7]
        (solve' 5 [(1,5,4), (1,3,1), (1,3,4), (3,1,5), (4,2,5)])
  ]

testBig :: Test
testBig  =  TestList "TestBig"
  [
    Test "1" $ assertEq (replicate n (m+1)) (solve' 2 (replicate n (1,2,m))),
    Test "2" $ assertEq (replicate n (2 * (2 * m - 2))) (solve' m (replicate n (m,1,m)))
  ]
  where
    n  =  10^5
    m  =  10^8

test :: IO ()
test  =  mapM_ run
  [
    testEmpty,
    testOnePeople,
    testInput,
    testBig
  ]
-}
--------------------------------------------------------------------------------

solve' :: Int -> [(Int, Int, Int)] -> [Int]
solve' n  =  map (solve n)

solve :: Int -> (Int, Int, Int) -> Int
solve n (s, f, time)
  | s < f && time < s  =  f - 1
  | s < f  =  period * (div time' period) + solve n (s, f, (mod time' period) - period')
  | s > f && time'' < period  =  period - f + 1
  | s > f  =  period * (div time'' period) + solve n (s, f, mod time'' period - period'')
  | otherwise  =  time
  where
    period  =  2 * (n - 1)
    time'  =  time + period'
    period'  =  period - s
    time''  =  time + period''
    period''  =  s - 2

reads :: IO [Int]
reads  =  getLine >>= return . map read . words

readPeople :: IO (Int, Int, Int)
readPeople  =  do
    [a, b, c]  <-  Main.reads
    return (a, b, c)

main :: IO ()
main  =  do
    [n, m]  <-  Main.reads
    mapM_ (const (readPeople >>= print . (solve m))) [1..n]

module Main where

import Control.Monad

main = do
    [n, m] <- liftM ( map read . words ) getLine :: IO [Int]
    replicateM_ n $ do
        [s, f, t] <- liftM ( map read . words ) getLine :: IO [Int]
        let k1 = ( t + (s-1) + 2 * (m-1) - 1 ) `div` ( 2 * (m-1) )
            k2 = ( t - (s-1) + 2 * (m-1) - 1 ) `div` ( 2 * (m-1) )
            t' = if s == f
                then t
                else if s < f
                then 2 * k2 * (m-1) + (s-1)
                else 2 * k1 * (m-1) - (s-1)
        putStrLn $ show $ t' + abs (f - s)

import qualified Data.ByteString.Lazy.Char8 as C
import IO
import Data.Maybe
import Data.List

prints [] = return ()
prints (x:xs) = do print x; prints xs

elevTimes m pos = [pos - 1, 2 * m - pos - 1] ++ [ 2 * (m-1) + x | x <- elevTimes m pos ]

firstElevTime m pos under = numCycle * elevCycle + (fromJust $ find ((<=) modCycle) (elevTimes m pos))
	where
		elevCycle = 2 * (m-1)
		numCycle = under `div` elevCycle
		modCycle = under `mod` elevCycle

solve m [s,f,t]
	| s == f = t
	| otherwise = firstElevTime m f (firstElevTime m s t)

main = do
	input <- fmap (map (C.takeWhile (/='\r')) . C.lines) $ C.hGetContents stdin
	let [n,m] = map (fst . fromJust . C.readInt) . C.words $ input !! 0
	let info = map (map (fst . fromJust . C.readInt) . C.words) $ take n $ tail input
	prints $ map (solve m) info

{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances #-}
{-# OPTIONS_GHC -O2 #-}

import Data.List
import Data.Maybe
import Data.Char
import Data.Array.IArray
import Data.Array.Unboxed (UArray)
import Data.Int
import Data.Ratio
import Data.Bits
import Data.Function
import Data.Ord
--import Control.Monad.State
import Control.Monad
import Control.Applicative
import Data.ByteString.Char8 (ByteString)
import qualified Data.ByteString.Char8 as BS
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Map (Map)
import qualified Data.Map as Map
import Data.IntMap (IntMap)
import qualified Data.IntMap as IntMap
import Data.Sequence (Seq, (<|), (|>), (><), ViewL(..), ViewR(..))
import qualified Data.Sequence as Seq
import qualified Data.Foldable as F
import Data.Graph

parseInput = do
    n <- readInt
    m <- readInt
    peoples <- replicateM n $ do
        si <- readInt
        fi <- readInt
        ti <- readInt
        return (si, fi, ti)
    return (m, peoples)
  where
    readInt = state $ fromJust . BS.readInt . BS.dropWhile isSpace
    readInteger = state $ fromJust . BS.readInteger . BS.dropWhile isSpace
    readString = state $ BS.span (not . isSpace) . BS.dropWhile isSpace
    readLine = state $ BS.span (not . isEoln) . BS.dropWhile isEoln
    isEoln ch = ch == '\r' || ch == '\n'

main = BS.putStr =<< solve . evalState parseInput <$> BS.getContents

solve (m, peoples) = BS.unlines [ BS.pack $ show (solveCase m p) | p <- peoples]

solveCase m (s, f, t)
    | s < f     = solveCase' firstUp period t + (f - s)
    | s > f     = solveCase' firstDown period t + (s - f)
    | otherwise = t
  where
    firstUp = s - 1
    firstDown = m - s + (m - 1)
    period = 2 * (m - 1)

solveCase' first period time = head $ dropWhile (<time) [t, t + period..]
  where
    t = (time - first) `div` period * period + first

----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------

class (Monad m) => MonadState s m | m -> s where
	get :: m s
	put :: s -> m ()

modify :: (MonadState s m) => (s -> s) -> m ()
modify f = do
	s <- get
	put (f s)

gets :: (MonadState s m) => (s -> a) -> m a
gets f = do
	s <- get
	return (f s)

newtype State s a = State { runState :: s -> (a, s) }

instance Functor (State s) where
	fmap f m = State $ \s -> let
		(a, s') = runState m s
		in (f a, s')

instance Applicative (State s) where
    pure = return
    (<*>) = ap

instance Monad (State s) where
	return a = State $ \s -> (a, s)
	m >>= k  = State $ \s -> let
		(a, s') = runState m s
		in runState (k a) s'

instance MonadState s (State s) where
	get   = State $ \s -> (s, s)
	put s = State $ \_ -> ((), s)

evalState :: State s a -> s -> a
evalState m s = fst (runState m s)

execState :: State s a -> s -> s
execState m s = snd (runState m s)

mapState :: ((a, s) -> (b, s)) -> State s a -> State s b
mapState f m = State $ f . runState m

withState :: (s -> s) -> State s a -> State s a
withState f m = State $ runState m . f

state = State

{-# LANGUAGE TypeSynonymInstances #-}
{-# OPTIONS_GHC -O2 #-}
import Debug.Trace
import Data.List
import Control.Monad
import Data.Array
import Data.Char
class Expression a where scan' :: String -> a; showans :: a -> String
instance Expression Int where scan' = read; showans = show
instance Expression Char where scan' (x:_) = x;showans = (:[])
instance Expression Float where scan' = read;showans = show
instance Expression Double where scan' = read;showans = show
instance Expression Integer where scan' = read;showans = show
instance Expression String where scan' = id;showans = id
instance (Expression a,Expression b) => Expression (a,b) where
    scan' = (\(x:y:_) -> (scan' x,scan' y)).words;showans (x,y) = showans x++' ':showans y
instance (Expression a,Expression b,Expression c) => Expression (a,b,c) where
    scan' = (\(x:y:z:_) -> (scan' x,scan' y,scan' z)).words;showans (x,y,z) = showans x++' ':showans y++' ':showans z
instance (Expression a,Expression b,Expression c,Expression d) => Expression (a,b,c,d) where
    scan' = (\(w:x:y:z:_) -> (scan' w,scan' x,scan' y,scan' z)).words;showans (w,x,y,z) = showans w++' ':showans x++' ':showans y++' ':showans z
instance (Expression a,Expression b,Expression c,Expression d,Expression e) => Expression (a,b,c,d,e) where
    scan' = (\(v:w:x:y:z:_) -> (scan' v,scan' w,scan' x,scan' y,scan' z)).words;showans (v,w,x,y,z) = showans v++' ':showans w++' ':showans x++' ':showans y++' ':showans z
scan :: (Expression a) => IO a; scan = getLine>>=(return.scan')
scans :: (Expression a) => Int -> IO [a]; scans n = replicateM n scan
scanlist :: (Expression a) => IO [a]; scanlist = getLine>>=return.(map scan').words
scanlists :: (Expression a) => Int -> IO [[a]]; scanlists n = replicateM n scanlist
putAnsLn :: (Expression a) => a -> IO (); putAnsLn = putStrLn.showans
putAnsLns :: (Expression a) => [a] -> IO (); putAnsLns = mapM_ putAnsLn

data Dir = Up|Down deriving (Eq,Show)
revd Up = Down
revd Down = Up

solve :: Int -> Int -> Int -> IO ()
solve c m n = do (s,f,t) <- scan :: IO (Int,Int,Int)
                 let now = mod t c
                     (nowstair,dir) = if now<m then (now+1,Up) else (c-now+1,Down)
                     dir2 = if (dir==Up&&nowstair>s)||(dir==Down&&nowstair<s) then revd dir else dir
                     dist1 = if dir==Up then
                                 if nowstair>s then 2*m-nowstair-s else s-nowstair
                             else
                                 if nowstair<s then nowstair+s-2 else nowstair-s
                     dist2 = if dir2==Up then
                                 if s>f then 2*m-s-f else f-s
                             else
                                 if s<f then s+f-2 else s-f
                 print (if s==f then t else (dist1 + dist2 + t))
                 when (n/=1) (solve c m (n-1))

main = do (n,m) <- scan :: IO (Int,Int)
          solve (2*m-2) m n

q m[s,f,pt]|s==f=t|f<s=m+q m[m-s,m-f,pt-m]|1>0=(t-s+c-1)`div`c*c+f where c=2*m;t=succ pt
s([_,m]:l)=map(q m)l
main=interact$unlines.map show.s.map(map(pred.read).words).lines

{-# LANGUAGE TypeSynonymInstances #-}
{-# OPTIONS_GHC -O2 #-}
import Debug.Trace
import Data.List
import Control.Monad
import Data.Array
import Data.Char
class Expression a where scan' :: String -> a; showans :: a -> String
instance Expression Int where scan' = read; showans = show
instance Expression Char where scan' (x:_) = x;showans = (:[])
instance Expression Float where scan' = read;showans = show
instance Expression Double where scan' = read;showans = show
instance Expression Integer where scan' = read;showans = show
instance Expression String where scan' = id;showans = id
instance (Expression a,Expression b) => Expression (a,b) where
    scan' = (\(x:y:_) -> (scan' x,scan' y)).words;showans (x,y) = showans x++' ':showans y
instance (Expression a,Expression b,Expression c) => Expression (a,b,c) where
    scan' = (\(x:y:z:_) -> (scan' x,scan' y,scan' z)).words;showans (x,y,z) = showans x++' ':showans y++' ':showans z
instance (Expression a,Expression b,Expression c,Expression d) => Expression (a,b,c,d) where
    scan' = (\(w:x:y:z:_) -> (scan' w,scan' x,scan' y,scan' z)).words;showans (w,x,y,z) = showans w++' ':showans x++' ':showans y++' ':showans z
instance (Expression a,Expression b,Expression c,Expression d,Expression e) => Expression (a,b,c,d,e) where
    scan' = (\(v:w:x:y:z:_) -> (scan' v,scan' w,scan' x,scan' y,scan' z)).words;showans (v,w,x,y,z) = showans v++' ':showans w++' ':showans x++' ':showans y++' ':showans z
scan :: (Expression a) => IO a; scan = getLine>>=(return.scan')
scans :: (Expression a) => Int -> IO [a]; scans n = replicateM n scan
scanlist :: (Expression a) => IO [a]; scanlist = getLine>>=return.(map scan').words
scanlists :: (Expression a) => Int -> IO [[a]]; scanlists n = replicateM n scanlist
putAnsLn :: (Expression a) => a -> IO (); putAnsLn = putStrLn.showans
putAnsLns :: (Expression a) => [a] -> IO (); putAnsLns = mapM_ putAnsLn

data Dir = Up|Down deriving (Eq,Show)

solve :: Int -> Int -> [(Int,Int,Int)] -> [Int]
solve _ _ [] = []
solve c m ((s,f,t):xs) = let now = mod (t+1) c
                             (nowstair,dir) = if now<=m then (now,Up) else (c-now+2,Down)
                             dist1 = if dir==Up then
                                         if nowstair>s then 2*m-nowstair-s else s-nowstair
                                     else
                                         if nowstair<s then nowstair+s-2 else nowstair-s
                             dist2 = if dir==Up then
                                         if s>f then 2*m-s-f else f-s
                                     else
                                         if s<f then s+f-2 else s-f
                         in
                           (if s==f then 0 else (dist1 + dist2 + t)):(solve c m xs)

main = do (n,m) <- scan :: IO (Int,Int)
          l <- scans n :: IO [(Int,Int,Int)]
          putAnsLns (solve (2*m-2) m l)

{-# LANGUAGE TypeSynonymInstances #-}
{-# OPTIONS_GHC -O2 #-}
import Debug.Trace
import Data.List
import Control.Monad
import Data.Array
import Data.Char
class Expression a where scan' :: String -> a; showans :: a -> String
instance Expression Int where scan' = read; showans = show
instance Expression Char where scan' (x:_) = x;showans = (:[])
instance Expression Float where scan' = read;showans = show
instance Expression Double where scan' = read;showans = show
instance Expression Integer where scan' = read;showans = show
instance Expression String where scan' = id;showans = id
instance (Expression a,Expression b) => Expression (a,b) where
    scan' = (\(x:y:_) -> (scan' x,scan' y)).words;showans (x,y) = showans x++' ':showans y
instance (Expression a,Expression b,Expression c) => Expression (a,b,c) where
    scan' = (\(x:y:z:_) -> (scan' x,scan' y,scan' z)).words;showans (x,y,z) = showans x++' ':showans y++' ':showans z
instance (Expression a,Expression b,Expression c,Expression d) => Expression (a,b,c,d) where
    scan' = (\(w:x:y:z:_) -> (scan' w,scan' x,scan' y,scan' z)).words;showans (w,x,y,z) = showans w++' ':showans x++' ':showans y++' ':showans z
instance (Expression a,Expression b,Expression c,Expression d,Expression e) => Expression (a,b,c,d,e) where
    scan' = (\(v:w:x:y:z:_) -> (scan' v,scan' w,scan' x,scan' y,scan' z)).words;showans (v,w,x,y,z) = showans v++' ':showans w++' ':showans x++' ':showans y++' ':showans z
scan :: (Expression a) => IO a; scan = getLine>>=(return.scan')
scans :: (Expression a) => Int -> IO [a]; scans n = replicateM n scan
scanlist :: (Expression a) => IO [a]; scanlist = getLine>>=return.(map scan').words
scanlists :: (Expression a) => Int -> IO [[a]]; scanlists n = replicateM n scanlist
putAnsLn :: (Expression a) => a -> IO (); putAnsLn = putStrLn.showans
putAnsLns :: (Expression a) => [a] -> IO (); putAnsLns = mapM_ putAnsLn

data Dir = Up|Down deriving (Eq,Show)

solve :: Int -> Int -> [(Int,Int,Int)] -> [Int]
solve _ _ [] = []
solve c m ((s,f,t):xs) = let now = mod (t+1) c
                             (nowstair,dir) = if now<m then (now,Up) else (c-m+2,Down)
                             dist1 = if dir==Up then
                                         if nowstair>s then 2*m-nowstair-s else s-nowstair
                                     else
                                         if nowstair<s then nowstair+s-2 else nowstair-s
                             dist2 = if dir==Up then
                                         if s>f then 2*m-s-f else f-s
                                     else
                                         if s<f then s+f-2 else s-f-1
                         in
                           (if s==f then 0 else (dist1 + dist2 + t)):(solve c m xs)

main = do (n,m) <- scan :: IO (Int,Int)
          l <- scans n :: IO [(Int,Int,Int)]
          putAnsLns (solve (2*m-2) m l)

{-# LANGUAGE TypeSynonymInstances #-}
{-# OPTIONS_GHC -O2 #-}
import Debug.Trace
import Data.List
import Control.Monad
import Data.Array
import Data.Char
class Expression a where scan' :: String -> a; showans :: a -> String
instance Expression Int where scan' = read; showans = show
instance Expression Char where scan' (x:_) = x;showans = (:[])
instance Expression Float where scan' = read;showans = show
instance Expression Double where scan' = read;showans = show
instance Expression Integer where scan' = read;showans = show
instance Expression String where scan' = id;showans = id
instance (Expression a,Expression b) => Expression (a,b) where
    scan' = (\(x:y:_) -> (scan' x,scan' y)).words;showans (x,y) = showans x++' ':showans y
instance (Expression a,Expression b,Expression c) => Expression (a,b,c) where
    scan' = (\(x:y:z:_) -> (scan' x,scan' y,scan' z)).words;showans (x,y,z) = showans x++' ':showans y++' ':showans z
instance (Expression a,Expression b,Expression c,Expression d) => Expression (a,b,c,d) where
    scan' = (\(w:x:y:z:_) -> (scan' w,scan' x,scan' y,scan' z)).words;showans (w,x,y,z) = showans w++' ':showans x++' ':showans y++' ':showans z
instance (Expression a,Expression b,Expression c,Expression d,Expression e) => Expression (a,b,c,d,e) where
    scan' = (\(v:w:x:y:z:_) -> (scan' v,scan' w,scan' x,scan' y,scan' z)).words;showans (v,w,x,y,z) = showans v++' ':showans w++' ':showans x++' ':showans y++' ':showans z
scan :: (Expression a) => IO a; scan = getLine>>=(return.scan')
scans :: (Expression a) => Int -> IO [a]; scans n = replicateM n scan
scanlist :: (Expression a) => IO [a]; scanlist = getLine>>=return.(map scan').words
scanlists :: (Expression a) => Int -> IO [[a]]; scanlists n = replicateM n scanlist
putAnsLn :: (Expression a) => a -> IO (); putAnsLn = putStrLn.showans
putAnsLns :: (Expression a) => [a] -> IO (); putAnsLns = mapM_ putAnsLn

data Dir = Up|Down deriving (Eq,Show)

solve :: Int -> Int -> [(Int,Int,Int)] -> [Int]
solve _ _ [] = []
solve c m ((s,f,t):xs) = let now = mod (t+1) c
                             (nowstair,dir) = if now<m then (now,Up) else (c-now+2,Down)
                             dist1 = if dir==Up then
                                         if nowstair>s then 2*m-nowstair-s else s-nowstair
                                     else
                                         if nowstair<s then nowstair+s-2 else nowstair-s
                             dist2 = if dir==Up then
                                         if s>f then 2*m-s-f else f-s
                                     else
                                         if s<f then s+f-2 else s-f
                         in
                           (if s==f then 0 else (dist1 + dist2 + t)):(solve c m xs)

main = do (n,m) <- scan :: IO (Int,Int)
          l <- scans n :: IO [(Int,Int,Int)]
          putAnsLns (solve (2*m-2) m l)

{-# LANGUAGE TypeSynonymInstances #-}
{-# OPTIONS_GHC -O2 #-}
import Debug.Trace
import Data.List
import Control.Monad
import Data.Array
import Data.Char
class Expression a where scan' :: String -> a; showans :: a -> String
instance Expression Int where scan' = read; showans = show
instance Expression Char where scan' (x:_) = x;showans = (:[])
instance Expression Float where scan' = read;showans = show
instance Expression Double where scan' = read;showans = show
instance Expression Integer where scan' = read;showans = show
instance Expression String where scan' = id;showans = id
instance (Expression a,Expression b) => Expression (a,b) where
    scan' = (\(x:y:_) -> (scan' x,scan' y)).words;showans (x,y) = showans x++' ':showans y
instance (Expression a,Expression b,Expression c) => Expression (a,b,c) where
    scan' = (\(x:y:z:_) -> (scan' x,scan' y,scan' z)).words;showans (x,y,z) = showans x++' ':showans y++' ':showans z
instance (Expression a,Expression b,Expression c,Expression d) => Expression (a,b,c,d) where
    scan' = (\(w:x:y:z:_) -> (scan' w,scan' x,scan' y,scan' z)).words;showans (w,x,y,z) = showans w++' ':showans x++' ':showans y++' ':showans z
instance (Expression a,Expression b,Expression c,Expression d,Expression e) => Expression (a,b,c,d,e) where
    scan' = (\(v:w:x:y:z:_) -> (scan' v,scan' w,scan' x,scan' y,scan' z)).words;showans (v,w,x,y,z) = showans v++' ':showans w++' ':showans x++' ':showans y++' ':showans z
scan :: (Expression a) => IO a; scan = getLine>>=(return.scan')
scans :: (Expression a) => Int -> IO [a]; scans n = replicateM n scan
scanlist :: (Expression a) => IO [a]; scanlist = getLine>>=return.(map scan').words
scanlists :: (Expression a) => Int -> IO [[a]]; scanlists n = replicateM n scanlist
putAnsLn :: (Expression a) => a -> IO (); putAnsLn = putStrLn.showans
putAnsLns :: (Expression a) => [a] -> IO (); putAnsLns = mapM_ putAnsLn

data Dir = Up|Down deriving (Eq,Show)

solve :: Int -> Int -> [(Int,Int,Int)] -> [Int]
solve _ _ [] = []
solve c m ((s,f,t):xs) = let now = mod (t+1) c
                             (nowstair,dir) = if now<m then (now,Up) else (c-now+2,Down)
                             dist1 = if dir==Up then
                                         if nowstair>s then 2*m-nowstair-s else s-nowstair
                                     else
                                         if nowstair<s then nowstair+s-2 else nowstair-s
                             dist2 = if dir==Up then
                                         if s>f then 2*m-s-f else f-s
                                     else
                                         if s<f then s+f-2 else s-f
                         in
                           (if s==f then t else (dist1 + dist2 + t)):(solve c m xs)

main = do (n,m) <- scan :: IO (Int,Int)
          l <- scans n :: IO [(Int,Int,Int)]
          putAnsLns (solve (2*m-2) m l)

q m[s,f,pt]|s==f=t|f<s=m+q m[m-s,m-f,t-m]|1>0=(t-s+c-1)`div`c*c+f where c=2*m;t=succ pt
s([_,m]:l)=map(q$m)l
main=interact$unlines.map show.s.map(map(pred.read).words).lines


import Data.List
import qualified Data.Set as Set

partitionaAtNotSuccessive _ [] = ([], [])
partitionaAtNotSuccessive _ [x] = ([x], [])
partitionaAtNotSuccessive next (x : xs)
                            | next x == head xs = (x : fst t, snd t)
                            | otherwise = ([x], xs)
                                where t = partitionaAtNotSuccessive next xs

f :: Int -> [Int] -> Set.Set Int -> [[Int]]
f _ [] _ = []
f n (x:xs) p
--    | n == x = successive : f (succ (last successive)) xs (Set.fromList notSuccessive)
--    | otherwise = [] : f n xs (Set.insert x p)
--                            where (successive, notSuccessive) = partitionaAtNotSuccessive succ (Set.toList (Set.insert x p))
--
    | n == x = successive : f (succ lastSuccessive) xs (notSuccessive)
    | otherwise = [] : f n xs nextP
                            where nextP = Set.insert x p
                                  successive = takeWhile ((flip Set.member) nextP) [n..]
                                  lastSuccessive = last successive
                                  notSuccessive = snd (Set.split lastSuccessive nextP)

main = do
        nS <- getLine
        snacksS <- getLine
        let n = read nS :: Int
            snacks = map (n - ) (map read (words snacksS) :: [Int])
        putStr (unlines
                (map unwords
                        (map
                         (map (\x -> show (n - x)))
                            (f 0 snacks Set.empty)
                        )
                    )
                )

import Control.Applicative( (<$>))
import Data.IntSet( deleteFindMax, insert, empty, null)
import qualified Data.IntSet as IS
main = do
    n_ <- readLn
    ns_ <- map read . words <$> getLine
    let
	proc _	_	[]  = []
	proc st next (n:ns)
	  | n==next	    = let
			    (dmp,st',next') = dump [] st (next-1)
			in
			    (n:reverse dmp):(proc st' next' ns)
	  | otherwise	    = []:(proc (insert n st) next ns)
	dump v st   next
	  | IS.null st	    = (v,empty,next)
	  | otherwise	    = let
				(mx,st') = deleteFindMax st
			    in
				if mx==next
				    then dump (mx:v) st' (next-1)
				    else (v, st, next)

	putStrs [] = putStrLn ""
	putStrs (x:xs) = (putStr $ (show x)++" ") >> putStrs xs
	print' [] = return ()
	print' (x:xs) = putStrs x >> print' xs

    print' $ proc empty n_ ns_

-- 767A

import Data.Functor ((<$>))
import Control.Monad.State

checkHeap :: (Int, MaxSkewHeap) -> StateT (Int, MaxSkewHeap) IO ()
checkHeap (i, oldHeap) = do
  case pop oldHeap of
    Just (top, newHeap) ->
      if i == top
      then do
        liftIO . putStr $ ' ':(show top)
        checkHeap (i - 1, newHeap)
      else put (i, oldHeap)
    Nothing -> put (i, oldHeap)

addValue :: Int -> StateT (Int, MaxSkewHeap) IO ()
addValue x = do
  (i, heap) <- get
  if i == x
  then do
    liftIO . putStr $ show i
    checkHeap (i - 1, heap)
  else put $ (i, insert x heap)
  liftIO . putChar $ '\n'

main :: IO ()
main = do
  _ <- getLine
  nums <- fmap read <$> words <$> getLine
  evalStateT (mapM_ addValue nums) (length nums, Empty)

data MaxSkewHeap = Empty | Node Int MaxSkewHeap MaxSkewHeap

(∪) :: MaxSkewHeap -> MaxSkewHeap -> MaxSkewHeap
(∪) l Empty = l
(∪) Empty r = r
(∪) l@(Node lval l1 r1) r@(Node rval l2 r2)
   | predicate lval rval = Node lval (r ∪ r1) l1
   | otherwise = Node rval (l ∪ r2) l2
   where predicate = (>)

insert :: Int -> MaxSkewHeap -> MaxSkewHeap
insert x heap = (Node x Empty Empty) ∪ heap

pop :: MaxSkewHeap -> Maybe (Int, MaxSkewHeap)
pop Empty = Nothing
pop (Node x l r) = Just (x, l ∪ r)

module Main where

import Control.Monad
import Control.Applicative
import qualified Data.ByteString.Char8 as B
import qualified Data.Set as S
import Data.List

readInt = maybe undefined fst . B.readInt
readInts = map readInt . B.words

fst3 (a, b, c) = a
solve n = reverse . fst3 . foldl' (\(dds, inits, maxi) x -> let
  inits' = S.insert x inits
  ds = takeWhile (`S.member` inits') [maxi, maxi - 1..1]
  in (ds:dds, inits', maxi - length ds)) ([], S.empty, n)

main = do
  n <- readInt <$> B.getLine
  xs <- readInts <$> B.getLine
  putStrLn . intercalate "\n" . map (intercalate " " . map show) $ solve n xs

import Data.List
import Data.Tree
import Data.Int
import Data.Maybe
import Data.Char
import Control.Monad
import Control.Monad.ST.Safe
import Control.Arrow
import Data.Array
import Data.Array.ST.Safe
import Data.STRef
import qualified Data.Map as Map
import qualified Data.Set as Set
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as C
main=   readsolveprint
readsolveprint::IO()
readsolveprint =  readLn >>= \n -> solve.(++) [n].map (fst.fromJust.C.readInt).C.words=<< C.getLine
solve::[Int]->IO ()
solve (x:xs) = foldM_ (\b a -> let pr = f b a in putStrLn (unwords $ map show pr) >> return (slv1 b a pr) ) (x,Set.empty)  $  xs
  where f (z1,z2) z3 = if z3==z1 then z3:slv2 z2 (z3-1) else []
slv1 (b, bs) x [] = (b,Set.insert x bs)
slv1 (b, bs) x ys = (b-length ys, bs)
slv2 ss1 0 =[]
slv2 ss1 x = let i = fromMaybe (-1) $ Set.lookupIndex (x) ss1 in if i/=(-1) then (x:slv2 ss1 (x-1)) else []

module Main where

import Control.Monad
import Control.Applicative
import qualified Data.ByteString.Char8 as B
import Data.List

readInt = maybe undefined fst . B.readInt
readInts = map readInt . B.words

fst4 (a, b, c, d) = a
solve n = reverse . fst4 . foldl' (\(ds, maxi, mini, s) x ->
  let mini' = min x mini
      s' = x:s
  in if x < maxi then ([]:ds, maxi, mini', s') else (s':ds, mini' - 1, mini', [])) ([], n, n, [])

main = do
  n <- readInt <$> B.getLine
  xs <- readInts <$> B.getLine
  putStrLn . intercalate "\n" . map (intercalate " " . map show) $ solve n xs

import Data.List
import Data.Tree
import Data.Int
import Data.Maybe
import Data.Char
import Control.Monad
import Control.Monad.ST.Safe
import Control.Arrow
import Data.Array
import Data.Array.ST.Safe
import Data.STRef
import qualified Data.Map as Map
import qualified Data.Set as Set
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as C
main=   readsolveprint
readsolveprint::IO()
readsolveprint =  readLn >>= \n -> solve.(++) [n].map (fst.fromJust.C.readInt).C.words=<< C.getLine
solve::[Int]->IO ()
solve (x:xs) = foldM_ (\b (a1,a2) -> putStrLn (f (a1,a2) b) >> return (if a2==Set.empty then a1 else b) ) (x+1)  $ zip [x,(x-1)..] $ zipWith (\ a b -> a Set.\\ b)(map Set.fromList $ tail $ inits xs) (map Set.fromList $ tail $ inits [x,(x-1)..])
  where f (z11,z12) z2 = unwords $ map show $ if z12==Set.empty then tail $ reverse [z11 .. z2] else []


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

data NodeType = BUD | LEAVE deriving (Eq, Show)
type NodeId = Int
type Parent = Maybe NodeId
type BudCount = Int
type LeaveCount = Int
type LonelyRoot = Bool
data NodeCount = NC !BudCount !LeaveCount deriving (Eq, Show)

instance Semigroup NodeCount where
  (NC bc lc) <> (NC bc' lc') = NC (bc + bc') (lc + lc')

instance Monoid NodeCount where
  mempty = NC 0 0

mainFun :: SP Builder
mainFun = do
  ~[t] <- getInts 1
  fmap mconcat $ replicateM t $ do
    ~[n] <- getInts 1
    es <- replicateM (n - 1) $ getInts 2
    let
      esArr :: Array NodeId [NodeId]
      esArr = accumArray (flip (:)) [] (1, n) $ do
        [u, v] <- es
        [(u, v), (v, u)]
      countNode :: Parent -> NodeId -> (NodeType, NodeCount)
      countNode p i = (nodeType, nodeCount)
        where
          children = maybe id (filter . (/=)) p $ esArr!i
          childCounts = map (countNode (Just i)) children
          nodeType
            | null children = LEAVE
            | any ((==LEAVE) . fst) childCounts = BUD
            | otherwise = LEAVE
          nodeCount = foldMap snd childCounts <> (case nodeType of
            LEAVE -> NC 0 1
            BUD -> NC 1 0)
      (rootType, NC budCount leaveCount) = countNode Nothing 1
    pure $! putInts [leaveCount - budCount + (if rootType == LEAVE then 0 else 1)]

type SP = State [P.ByteString]

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

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

getInts :: Int -> SP [Int]
getInts k = map 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 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.Bool (bool)
import Data.Maybe
import Data.Bifunctor (bimap)

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

data NodeType = BUD | LEAVE deriving (Eq, Show)
type NodeId = Int
type Parent = NodeId
type BudCount = Int
type LeaveCount = Int

mainFun :: SP Builder
mainFun = do
  ~[t] <- getInts 1
  fmap mconcat $ replicateM t $ do
    ~[n] <- getInts 1
    es <- fmap concat $ replicateM (n - 1) $ do
      ~[u, v] <- getInts 2
      pure $! [(u, v), (v, u)]
    let
      esArr :: Array NodeId [NodeId]
      esArr = accumArray (flip (:)) [] (1, n) es
      countNode :: Parent -> NodeId -> (NodeType, (BudCount, LeaveCount))
      countNode p i = (nodeType, (bc + (fromEnum $ nodeType == BUD), lc + (fromEnum $ nodeType == LEAVE)))
        where
          children =  map (countNode i) $ filter (/=p) $ esArr!i
          nodeType = bool LEAVE BUD $ any ((==LEAVE) . fst) children
          (bc, lc) = bimap sum sum $ unzip $ fmap snd $ children
      (rootType, (budCount, leaveCount)) = countNode 1 1
    pure $! putInts [leaveCount - budCount + (fromEnum $ rootType == BUD)]

type SP = State [P.ByteString]

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

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

getInts :: Int -> SP [Int]
getInts k = map 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 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

data NodeType = BUD | LEAVE deriving (Eq, Show)
type NodeId = Int
type Parent = NodeId
type BudCount = Int
type LeaveCount = Int
type LonelyRoot = Bool
data NodeCount = NC !BudCount !LeaveCount deriving (Eq, Show)

instance Semigroup NodeCount where
  (NC bc lc) <> (NC bc' lc') = NC (bc + bc') (lc + lc')

instance Monoid NodeCount where
  mempty = NC 0 0

mainFun :: SP Builder
mainFun = do
  ~[t] <- getInts 1
  fmap mconcat $ replicateM t $ do
    ~[n] <- getInts 1
    es <- fmap concat $ replicateM (n - 1) $ do
      ~[u, v] <- getInts 2
      pure $! [(u, v), (v, u)]
    let
      esArr :: Array NodeId [NodeId]
      esArr = accumArray (flip (:)) [] (1, n) es
      countNode :: Parent -> NodeId -> (NodeType, NodeCount)
      countNode p i = (nodeType, nodeCount)
        where
          children = filter (/=p) $ esArr!i
          childCounts = map (countNode i) children
          nodeType = if any ((==LEAVE) . fst) childCounts then BUD else LEAVE
          nodeCount = foldMap snd childCounts <> (
            NC (fromEnum $ nodeType == BUD) (fromEnum $ nodeType == LEAVE))
      (rootType, NC budCount leaveCount) = countNode 1 1
    pure $! putInts [leaveCount - budCount + (fromEnum $ rootType == BUD)]

type SP = State [P.ByteString]

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

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

getInts :: Int -> SP [Int]
getInts k = map 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 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

data NodeType = BUD | LEAVE deriving (Eq, Show)
type NodeId = Int
type Parent = NodeId
type BudCount = Int
type LeaveCount = Int
type LonelyRoot = Bool
data NodeCount = NC !BudCount !LeaveCount deriving (Eq, Show)

instance Semigroup NodeCount where
  (NC bc lc) <> (NC bc' lc') = NC (bc + bc') (lc + lc')

instance Monoid NodeCount where
  mempty = NC 0 0

mainFun :: SP Builder
mainFun = do
  ~[t] <- getInts 1
  fmap mconcat $ replicateM t $ do
    ~[n] <- getInts 1
    es <- replicateM (n - 1) $ getInts 2
    let
      esArr :: Array NodeId [NodeId]
      esArr = accumArray (flip (:)) [] (1, n) $ do
        [u, v] <- es
        [(u, v), (v, u)]
      countNode :: Parent -> NodeId -> (NodeType, NodeCount)
      countNode p i = (nodeType, nodeCount)
        where
          children = filter (/=p) $ esArr!i
          childCounts = map (countNode i) children
          nodeType = if any ((==LEAVE) . fst) childCounts then BUD else LEAVE
          nodeCount = foldMap snd childCounts <> (
            NC (fromEnum $ nodeType == BUD) (fromEnum $ nodeType == LEAVE))
      (rootType, NC budCount leaveCount) = countNode 1 1
    pure $! putInts [leaveCount - budCount + (fromEnum $ rootType == BUD)]

type SP = State [P.ByteString]

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

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

getInts :: Int -> SP [Int]
getInts k = map 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 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

data NodeType = BUD | LEAVE deriving (Eq, Show)
type NodeId = Int
type Parent = Maybe NodeId
type BudCount = Int
type LeaveCount = Int
type LonelyRoot = Bool
data NodeCount = NC !BudCount !LeaveCount deriving (Eq, Show)

instance Semigroup NodeCount where
  (NC bc lc) <> (NC bc' lc') = NC (bc + bc') (lc + lc')

instance Monoid NodeCount where
  mempty = NC 0 0

mainFun :: SP Builder
mainFun = do
  ~[t] <- getInts 1
  fmap mconcat $ replicateM t $ do
    ~[n] <- getInts 1
    es <- replicateM (n - 1) $ getInts 2
    let
      esArr :: Array NodeId [NodeId]
      esArr = accumArray (flip (:)) [] (1, n) $ do
        [u, v] <- es
        [(u, v), (v, u)]
      countNode :: Parent -> NodeId -> (NodeType, NodeCount, LonelyRoot)
      countNode p i = (nodeType, nodeCount, lonelyRoot)
        where
          children = maybe id (filter . (/=)) p $ esArr!i
          childCounts = map (countNode (Just i)) children
          nodeType
            | null children = LEAVE
            | any ((==LEAVE) . (\(t, _, _) -> t)) childCounts = BUD
            | otherwise = LEAVE
          nodeCount = foldMap (\(_, c, _) -> c) childCounts <> (case nodeType of
            LEAVE -> NC 0 1
            BUD -> NC 1 0)
          lonelyRoot = isNothing p && nodeType == LEAVE
      (_, NC budCount leaveCount, lonelyRoot) = countNode Nothing 1
    pure $! putInts [leaveCount - budCount + (if lonelyRoot then 0 else 1)]

type SP = State [P.ByteString]

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

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

getInts :: Int -> SP [Int]
getInts k = map 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
import Data.Array
import Data.Graph
import Data.Maybe
import Data.Tree
import qualified Data.ByteString.Char8 as C

data Typ = Leaf | Bud deriving Eq

solve :: IO ()
solve = do
    [n] <- readInts
    es <- replicateM (n - 1) readInts
    let [t] = dfs (buildG (1, n) $ concatMap (\[u, v] -> [(u, v), (v, u)]) es) [1]
        ta = array (1, n) $ go t [] where
            go (Node u ts) acc = (u, typ) : foldr go acc ts where
                typ | any ((==Leaf) . (ta!) . rootLabel) ts = Bud
                    | otherwise                             = Leaf
    print $ n - 2 * length (filter (==Bud) $ elems ta) + fromEnum (ta!1 == Bud)

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

main :: IO ()
main = readInts >>= flip replicateM_ solve . head

{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE RecordWildCards #-}

import Control.Applicative (liftA2)
import Control.Arrow ((>>>))
import Control.Monad
import Control.Monad.State (State, evalState, get, gets, put)
import qualified Data.ByteString.Lazy.Char8 as C
import Data.Function
import Data.Int
import Data.List
import Data.Maybe
import Data.Array
import Data.Tuple (swap)
import Data.Bool (bool)

main :: IO ()
main = C.interact $ runScanner (numberOf input) >>> map (solve >>> output) >>> C.unlines

data TC = TC { n :: Int, edges :: [(Int, Int)] }

input :: Scanner TC
input = do
  n <- int
  edges <- (n - 1) >< pair int int
  return TC{..}

output = showB

solve :: TC -> Int
solve TC{..} = n - 2 * b + bool 1 0 rb
  where
    adj :: Array Int [Int]
    adj = accumArray (flip (:)) [] (1, n) $ edges ++ map swap edges

    (b, rb) = dfs 1 1

    dfs :: Int -> Int -> (Int, Bool)
    dfs p u = (sum buds + bool 1 0 leaf, leaf)
      where
        leaf = not $ or leaves
        (buds, leaves) = unzip . map (dfs u) . filter (/= p) $ adj ! u

-------------------------- Template ------------------------------------------
-- Lists
groupOn :: Eq b => (a -> b) -> [a] -> [[a]]
groupOn = groupBy . on (==)

chunksOf :: Int -> [a] -> [[a]]
chunksOf _ [] = []
chunksOf k xs = let (hs, ts) = splitAt k xs in hs : chunksOf k ts

adjacents :: [a] -> [(a, a)]
adjacents xs = zip xs (tail xs)

adjacentsWith :: (a -> a -> b) -> [a] -> [b]
adjacentsWith f xs = zipWith f xs (tail xs)

count :: Eq a => a -> [a] -> Int
count = countBy . (==)

countBy :: (a -> Bool) -> [a] -> Int
countBy p = length . filter p

-- Scanner
type Scanner = State [C.ByteString]

runScanner :: Scanner a -> C.ByteString -> a
runScanner = runScannerWith C.words

runScannerWith :: (C.ByteString -> [C.ByteString]) -> Scanner a -> C.ByteString -> a
runScannerWith t s = evalState s . t

peek :: Scanner C.ByteString
peek = gets head

bstr :: Scanner C.ByteString
bstr = get >>= \case s : ss -> put ss >> return s

str :: Scanner String
str = C.unpack <$> bstr

readStr :: Read a => Scanner a
readStr = read <$> str

int :: Scanner Int
int = fst . fromJust . C.readInt <$> bstr

integer :: Scanner Integer
integer = readStr

int64 :: Scanner Int64
int64 = readStr

double :: Scanner Double
double = readStr

decimal :: Int -> Scanner Int
decimal p = round . ((10 ^ p) *) <$> double

numberOf :: Scanner a -> Scanner [a]
numberOf s = int >>= flip replicateM s

many :: Scanner a -> Scanner [a]
many s = get >>= \case [] -> return []; _ -> (:) <$> s <*> many s

till :: (C.ByteString -> Bool) -> Scanner a -> Scanner [a]
till p s = do
  t <- peek
  if p t
    then return []
    else (:) <$> s <*> till p s

times :: Int -> Scanner a -> Scanner [a]
times = replicateM

(><) = times

two, three, four :: Scanner a -> Scanner [a]
[two, three, four] = map times [2 .. 4]

pair :: Scanner a -> Scanner b -> Scanner (a, b)
pair = liftA2 (,)

showB :: Show a => a -> C.ByteString
showB = C.pack . show

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.ByteString.Builder.Extra (flush) -- for interactive problems
import Control.Monad
import Data.List
import Data.Array.Unboxed

type Graph = Array Int [Int]

dfs :: Graph -> Int -> Int -> [(Int, Int)] -> (Int, [(Int, Int)])
dfs adj par curr later = let
  children = filter (/= par) $ adj ! curr
  res = scanr (\child (_, cont) -> dfs adj curr child cont) (1, later) children
  nleaves = foldl' (\acc (x, _) -> acc + if  x == 0  then  1  else  0) 0 res
  in  case  res  of
  (_, cont) : _ -> (,) nleaves $ if  nleaves > 0
    then  (curr, nleaves) : cont
    else  cont
  _ -> error "scanr cannot result in []"

mainFun :: SO
mainFun = do
  ~[t] <- getInts 1
  fmap mconcat $ replicateM t $ do
    ~[n] <- getInts 1
    es <- fmap concat $ replicateM (n - 1) $ do
      ~[u, v] <- getInts 2
      pure [(u, v), (v, u)]
    let
      adj = accumArray (flip (:)) [] (1, n) es
      (_special, almostBuds) = dfs adj 1 1 []
      ans = foldl' (\x (_, y) -> x + y - 1) 1 almostBuds
    pure $ {- string7 (show almostBuds ++ "\n") <> -} putInts [ans]

type SP = State [P.ByteString]
type SO = SP Builder

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

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

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


{-# OPTIONS_GHC -O2 #-}

import Data.List
import Data.Char
import Control.Monad
import Data.Maybe
import Data.Int
import qualified Data.ByteString.Char8 as B

isSorted []       = True
isSorted [_]      = True
isSorted (x:y:xs) = x <= y && isSorted (y:xs)

testWith :: Int8 -> [Int8] -> Maybe String
testWith number array = if isSorted p1 && isSorted p2 && good then Just r else Nothing
  where
    ind = fromMaybe maxBound $ findIndex (>number) array
    r = zipWith (curry mapper) array [(0 :: Int)..]
    mapper (e, i)
      | e == number && i < ind = '2'
      | e == number && i > ind = '1'
      | e < number = '1'
      | e > number = '2'
    good = count number array <= (count number p1 + count number p2)
    (a1, a2) = (filter (<=number) array, filter(>=number) array)
    p1 = cutPInfBegin a1 number
    p2 = cutMInfEnd   a2 number
    count x =  length . filter (==x)

cutPInfBegin [] _ = []
cutPInfBegin x n = filter (/= n) x ++ takeWhile (== n) (reverse x)
cutMInfEnd [] _ = []
cutMInfEnd x n = takeWhile (== n) x ++ filter (/= n) x

solve a 0 = "-"
solve a n
  | Just s <- testWith n a = s
  | otherwise = solve a (n - 1)

d2i8 x = case x of
  '0' -> 0
  '1' -> 1
  '2' -> 2
  '3' -> 3
  '4' -> 4
  '5' -> 5
  '6' -> 6
  '7' -> 7
  '8' -> 8
  '9' -> 9

main = do
  Just (a, _) <- fmap B.readInt B.getLine
  replicateM_ a $ do
     _ <- B.getLine
     arr <- fmap (map d2i8 . filter isDigit . B.unpack) B.getLine
     B.putStrLn $ B.pack $ solve arr 9

import Data.List
--import Data.Ord
import Control.Monad
import Data.Maybe

isSorted []       = True
isSorted [_]      = True
isSorted (x:y:xs) = x <= y && isSorted (y:xs)

pinf = 10 :: Int
minf = -10 :: Int

testWith :: Int -> [Int] -> Maybe String
testWith number array = if isSorted p1 && isSorted p2 && good then Just r else Nothing
  where
    ind = fromMaybe maxBound $ findIndex (>number) array
    r = zipWith (curry mapper) array [(0 :: Int)..]
    mapper (e, i)
      | e == number && i < ind = '2'
      | e == number && i > ind = '1'
      | e < number = '1'
      | e > number = '2'
    good = count number array <= (count number p1 + count number p2)
    (a1, a2) = (filter (<=number) array, filter(>=number) array)
    p1 = cutPInfBegin a1 number
    p2 = cutMInfEnd   a2 number
    count x =  length . filter (==x)

cutPInfBegin [] _ = []
cutPInfBegin x n = filter (/= n) x ++ takeWhile (== n) (reverse x)
cutMInfEnd [] _ = []
cutMInfEnd x n = takeWhile (== n) x ++ filter (/= n) x

solve a 0 = "-"
solve a n
  | Just s <- testWith n a = s
  | otherwise = solve a (n - 1)

main = do
  a <- fmap read getLine :: IO Int
  forM_ [1..a] $ \_ -> do
     _ <- getLine
     arr <- fmap (map $ \x -> read [x]) getLine
     putStrLn $ solve arr 9

import Data.List
import Data.Char
import Control.Monad
import Data.Maybe
import qualified Data.ByteString.Char8 as B

isSorted []       = True
isSorted [_]      = True
isSorted (x:y:xs) = x <= y && isSorted (y:xs)

testWith :: Int -> [Int] -> Maybe String
testWith number array = if isSorted p1 && isSorted p2 && good then Just r else Nothing
  where
    ind = fromMaybe maxBound $ findIndex (>number) array
    r = zipWith (curry mapper) array [(0 :: Int)..]
    mapper (e, i)
      | e == number && i < ind = '2'
      | e == number && i > ind = '1'
      | e < number = '1'
      | e > number = '2'
    good = count number array <= (count number p1 + count number p2)
    (a1, a2) = (filter (<=number) array, filter(>=number) array)
    p1 = cutPInfBegin a1 number
    p2 = cutMInfEnd   a2 number
    count x =  length . filter (==x)

cutPInfBegin [] _ = []
cutPInfBegin x n = filter (/= n) x ++ takeWhile (== n) (reverse x)
cutMInfEnd [] _ = []
cutMInfEnd x n = takeWhile (== n) x ++ filter (/= n) x

solve a 0 = "-"
solve a n
  | Just s <- testWith n a = s
  | otherwise = solve a (n - 1)

main = do
  Just (a, _) <- fmap B.readInt B.getLine
  replicateM_ a $ do
     _ <- B.getLine
     arr <- fmap (map digitToInt . filter isDigit . B.unpack) B.getLine
     B.putStrLn $ B.pack $ solve arr 9

{-# LANGUAGE TypeApplications #-}

import Data.List
import Data.Ord
import Control.Monad
import Data.Maybe

lis a = extract1 (maximumBy (comparing $ \(_, (a, _, _)) -> a) (zip [0..] cmp)) cmp
  where cmp = lisHelper (tail a) [(1, head a, -1)]
        extract (_, _, -1) _ = []
        extract (1, _, l) _ = [l]
        extract (_, c, l) a = extract (a !! l) a ++ [l]
        extract1 (i, (_, c, -1)) a = [i]
        extract1 (i, (_, c, l)) a = extract (a !! l) a ++ [l] ++ [i]
        lisHelper []     acc = acc
        lisHelper (x:xs) acc = lisHelper xs $ acc ++ [max acc x]
        max acc x = (\((a, _, _), i) -> (a + 1, x, i)) $ maximumBy (comparing $ \((a, _, _), _) -> a) $ filter (\((_, e, _), _) -> e <= x) (zip ((0, -1, -1):acc) [(-1)..])

takeNot what whre = map snd $ filter (\(i, e) -> not $ i `elem` what) (zip [0..] whre)

isSorted []       = True
isSorted [x]      = True
isSorted (x:y:xs) = x <= y && isSorted (y:xs)

prc x = if s then Just $ map (\e -> if e `elem` l then '1' else '2') [0..(length x - 1)] else Nothing
  where l = lis x
        s = isSorted $ takeNot l x

main = do
  a <- fmap read getLine
  forM_ [1..a] $ \_ -> do
     _ <- getLine
     a <- fmap (map $ \x -> read [x]) getLine
     putStrLn $ fromMaybe "-" (prc a)


import System.IO (getChar, putStr)
import Data.Char

{--
getInt  :: Int -> IO Int

getInt x = do c <- getChar
              if isDigit c then getInt (10 * x + digitToInt c)
                         else return x
--}

getInt :: Int -> [Char] -> Int

getInt num (x : xs) = getInt (10 * num + digitToInt x) xs
getInt num _      = num

getString :: Int -> [Char]

getString x = let
                 q = x `div` 10
                 r = x `mod` 10
                 rem = chr $ ord '0' + r
              in if q > 0 then getString q ++ [rem]
                          else [rem]

findEven (x : xs) n = if x `mod` 2 == 0 then Just n
                                      else findEven xs $ n + 1
findEven _       _  = Nothing

solvet :: IO ()
solvet           = do n <- getLine
                      a <- getLine
                      putStr (let
                             line1 = words n
                             line2 = words a
                             l1    = head $ map (getInt 0) line1
                             l2    = map (getInt 0) line2
                             in  case findEven l2 1 of
                                (Just x) -> "1\n" ++ getString x ++ "\n"
                                _        -> if l1 == 1 then "-1\n"
                                                      else "2\n1 2\n")

solve :: Int -> IO ()

solve t | t > 0 = solve (t - 1) >> solvet
        | otherwise = putStr ""

main :: IO ()

main = do str <- getLine
          let
              q1 = words str
              q  = head $ map (getInt 0) q1
           in solve q

{--
          putStr (let
                 ls = words str
                 lsNum = map (getInt 0) ls
                 lsChar = map getString lsNum
                 in foldl (++) [] lsChar)
--}

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

main = getLine >>= test.read
test 0 = return ()
test i = do
  getLine
  as <- map read.words <$> getLine
  case () of
    _ | any even as     -> print 1 >> print (fst $ head $ filter (even.snd) $ zip [1..] as)
      | length as >= 2  -> putStrLn "2\n1 2"
      | otherwise       -> putStrLn "-1"
  test (i - 1)

import Data.List

main :: IO ()
main =
  interact
    (unlines .
     concatMap (map (unwords . map show) . solve . map read . words) .
     takeSnd . tail . lines)

takeSnd :: [a] -> [a]
takeSnd [] = []
takeSnd [x] = []
takeSnd (x:y:xs) = y : takeSnd xs

solve :: [Int] -> [[Int]]
solve l =
  maybe [[-1]] (\x -> [[length x], x]) (aux (map fst evens) (map fst odds))
  where
    (evens, odds) = partition (even . snd) (zip [1 ..] l)

aux :: [Int] -> [Int] -> Maybe [Int]
aux (x:xs) _ = Just [x]
aux _ (x:y:xs) = Just [x, y]
aux _ _ = Nothing

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

process1 c s | c==1 && odd (head s) = do
			putStrLn "-1"
	     |c==1  = do
			putStrLn "1"
			putStrLn "1"
	     | e>0  = do
			putStrLn "1"
			putStrLn $ show $ snd $ head $ filter (\z-> even (fst z)) $ zip s [1..]
	     | otherwise = do
			putStrLn "2"
			putStrLn $ intercalate " " $ map show $ map snd $ take 2 $ filter (\z-> odd(fst z)) $ zip s [1..]
	where e = length $ filter even  s

process = do
		c<-read <$> getLine ::IO Int
		s<-map read <$> words <$> getLine ::IO [Int]
		process1 c s

main = do
		n<-read <$> getLine ::IO Int
		replicateM_ n process

import Data.List(findIndex)
import Data.Maybe(isNothing,fromJust)

evenSubset :: [Int] -> Maybe [Int]
evenSubset xs
    | isNothing idx = if length xs == 1 then Nothing else Just [1,2]
    | otherwise = fmap ((:[]) . (+1)) idx
    where idx = findIndex even xs

process :: Int -> IO ()
process 0 = return ()
process t = do
    n' <- getLine
    a' <- getLine
    let a = map read . words $ a'
    let s = evenSubset a
    if isNothing s
        then print (-1)
        else do
            let s' = fromJust s
            print . length $ s'
            putStrLn . unwords . map show $ s'
    process (t-1)

main = do
    t <- fmap read getLine
    process t

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

process1 c s | c==1 = do
			putStrLn "-1"
	     |c==2 && even (sum s ) = do
			putStrLn "2"
			putStrLn "1 2"
	     | c==2 =do
			putStrLn "-1"
	     | o >2= do
			putStrLn "2"
			putStrLn $ intercalate " " $ map show $ map snd $ filter (\z-> odd(fst z)) $ zip s [1..]
	     | otherwise = do
			putStrLn "2"
			putStrLn $ intercalate " " $ map show $ map snd $ filter (\z-> even(fst z)) $ zip s [1..]
	where o = length $ filter odd s

process = do
		c<-read <$> getLine ::IO Int
		s<-map read <$> words <$> getLine ::IO [Int]
		process1 c s

main = do
		n<-read <$> getLine ::IO Int
		replicateM_ n process


{-# 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

main = readInt >>= flip replicateM solve >>= mapM_ print

solve = do
	[ a, b, c ] <- readInts
	return $ maximum $ do
		i <- [ 0 .. min a ( b `div` 2 ) ]
		let
			j = min ( b - 2 * i ) ( c `div` 2 )
		return $ i + 2 * i + j + 2 * j

{-# OPTIONS_GHC -O2 #-}
{-# LANGUAGE BangPatterns      #-}
{-# LANGUAGE CPP               #-}
{-# LANGUAGE LambdaCase        #-}
{-# LANGUAGE MultiWayIf        #-}
{-# LANGUAGE TupleSections     #-}
{-# LANGUAGE ViewPatterns      #-}
#ifndef DEBUG
{-# LANGUAGE Safe              #-}
#endif

import           Control.Applicative
import           Control.Exception
import           Control.Monad
import           Control.Monad.State.Strict
import qualified Data.Array                 as A
import qualified Data.Array.Unboxed         as UA
import qualified Data.Array.ST.Safe         as MA
import           Data.Bool
import qualified Data.ByteString.Builder    as B
import qualified Data.ByteString.Char8      as C
import           Data.Char
import           Data.Function
import qualified Data.IntMap.Strict         as IM
import qualified Data.IntSet                as IS
import qualified Data.List                  as L
import qualified Data.List.NonEmpty         as NL
import           Data.Monoid
import qualified Data.Map.Strict            as M
import           Data.Monoid
import           Data.Ord
import           Data.Semigroup
import qualified Data.Set                   as S
import           Data.Tuple
import           Foreign
import qualified System.IO                  as IO
#ifdef DEBUG
import           Debug.Trace
#endif

main :: IO ()
main = do
  t <- readLn
  replicateM_ t $ do
      [a,b,c] <- map read.words <$> getLine
      print $ maximum $ do
          x <- [0..min a (div b 2)]
          let b' = b - 2 * x
          y <- [0..min b' (div c 2)]
          return $ (x + y) * 3

import Control.Applicative
import Control.Monad
import Data.List
import Data.Maybe
import Data.Array
import qualified Data.Map as M

process  = do
		[a,b,c] <- map read <$> words <$> getLine ::IO [Int]
		let m1= min b (div c 2)
		let m2 = min a (div (b-m1) 2)
		print $ 3*(m1+m2)

main = do
		n<-read <$> getLine ::IO Int
		replicateM_ n   process

process :: Int -> Int -> Int -> Int
process a b c
    | 2*b <= c = 3*b
    | 2*a <= b' = 3*c2 + 3*a
    | otherwise = 3*c2 + 3*b2
    where
        c2 = c `div` 2
        b' = b-c2
        b2 = b' `div` 2

readInt :: String -> Int
readInt = read

main :: IO ()
main = do
    t <- fmap readInt getLine
    ts <- fmap (map (map readInt.words).lines) getContents
    mapM_ print $ map (\[a,b,c] -> process a b c) ts


import Control.Monad
import Data.Char
import Data.Int

solve :: Int64 -> Int
solve n
  | n `mod` 2050 /= 0 = -1
  | otherwise = bitsSum $ quot n 2050
  where
    bitsSum i = sum $ (\c -> ord c - ord '0') <$> show i

solveIO :: IO ()
solveIO = do
  l <- getLine
  let t = read l :: Int64
  putStr $ show (solve t) ++ "\n"

main :: IO ()
main = do
  l <- getLine
  let t = read l :: Int
  replicateM_ t solveIO

import qualified Data.List as L
import qualified Data.Map as M
import qualified Data.Set as S
import Control.Monad.ST

import qualified Data.Array as A

import Data.Bits(xor)

import Data.Array((!))

n2050 :: Integer -> Integer
n2050 n = aux 2050 where
	aux i
		| n < i = div i 10
		| otherwise = aux $ 10*i

solve :: Integer -> Maybe Integer
solve n = aux n where
	aux 0 = Just 0
	aux n | n < 2050 = Nothing
	aux n = do
		i <- aux (n - n2050 n)
		return $ i + 1

showR :: Maybe Integer -> Integer
showR Nothing = -1
showR (Just i) = i

main = do
	t <- getLine >>= return . read :: IO Integer
	let loop t = if t == 0 then return () else do
		n <- getLine >>= return . read :: IO Integer
		--a <- getLine >>= return . (fmap read) . words :: IO [Integer]
		print $ showR $ solve n
		loop $ t - 1
	loop t

import qualified Data.List as L
import qualified Data.Map as M
import qualified Data.Set as S
import Control.Monad.State.Strict

import qualified Data.Array as A

import Data.Bits(xor)

import Data.Array((!))

n2050 :: Integer -> Integer
n2050 n = aux 2050 where
	aux i
		| n < i = div i 10
		| otherwise = aux $ 10*i

solve :: Integer -> Maybe Integer
solve n = aux n where
	aux 0 = Just 0
	aux n | n < 2050 = Nothing
	aux n = do
		i <- aux (n - n2050 n)
		return $ i + 1

showR :: Maybe Integer -> Integer
showR Nothing = -1
showR (Just i) = i

main = do
	t <- getLine >>= return . read :: IO Integer
	let loop t = if t == 0 then return () else do
		n <- getLine >>= return . read :: IO Integer
		--a <- getLine >>= return . (fmap read) . words :: IO [Integer]
		print $ showR $ solve n
		loop $ t - 1
	loop t

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

import qualified Data.Array as A

import Data.Bits(xor)

import Data.Array((!))

n2050 :: Integer -> Integer
n2050 n = aux 2050 where
	aux i
		| n < i = div i 10
		| otherwise = aux $ 10*i

solve :: Integer -> Maybe Integer
solve n = aux n where
	aux 0 = Just 0
	aux n | n < 2050 = Nothing
	aux n = do
		i <- aux (n - n2050 n)
		return $ i + 1

showR :: Maybe Integer -> Integer
showR Nothing = -1
showR (Just i) = i

main = do
	t <- getLine >>= return . read :: IO Integer
	let loop t = if t == 0 then return () else do
		n <- getLine >>= return . read :: IO Integer
		--a <- getLine >>= return . (fmap read) . words :: IO [Integer]
		print $ showR $ solve n
		loop $ t - 1
	loop t

digitSum :: Integer -> Integer
digitSum v
  | v /= 0 = m + d
  | otherwise = 0
  where
    m = mod v 10
    d = digitSum $ div v 10

solve :: Integer -> Integer
solve val
  | m == 0 = digitSum d
  | otherwise = -1
  where
    m = mod val 2050
    d = div val 2050

operate :: IO()
operate = do
  line <- getLine
  let n = read line
  print $ solve n

solveAll :: Int -> IO()
solveAll n
  | n /= 0 = operate >> solveAll (n - 1)
  | otherwise = return ()

main :: IO ()
main = do
  line <- getLine
  let n = read line
  solveAll n

digitSum :: Integer -> Integer
digitSum v
  | v /= 0 = m + d
  | otherwise = 0
  where
    m = mod v 10
    d = digitSum $ div v 10

solve :: Integer -> Integer
solve val
  | m == 0 = digitSum d
  | otherwise = -1
  where
    m = mod val 2050
    d = div val 2050

solveAll :: [String] -> [String]
solveAll = map $ show . solve . read

main :: IO ()
main =
  interact $ unlines . solveAll . to_list
  where
    to_list = tail . words

digitSum :: Integer -> Integer
digitSum v
  | v /= 0 = m + d
  | otherwise = 0
  where
    m = mod v 10
    d = digitSum $ div v 10

solve :: [Integer] -> [Integer]
solve (val : xs)
  | m == 0 = digitSum d : next
  | otherwise = -1 : next
  where
    m = mod val 2050
    d = div val 2050
    next = solve xs
solve [] = []

main :: IO ()
main =
  interact $ to_string . solve . to_list
  where
    to_list = map read . tail . words
    to_string = unlines . map show

ns = takeWhile (<10^18) $ iterate (*10) 2050
solve n = case foldr (\x (r,ds) -> let (q,s) = r `divMod` x in (s,q:ds)) (n,[]) ns  of
    (a,_)  | a > 0 -> -1
    (_, b)         -> sum b

main = interact $ unlines . map (show . solve . (read :: String -> Integer )) .  tail . lines

solve n = case foldr (\x (r,ds) -> let (q,s) = r `divMod` x in (s,q:ds)) (n,[]) $ takeWhile (<10^18) $ iterate (*10) 2050  of
    (a,_)  | a > 0 -> -1
    (_, b)         -> sum b

main = interact $ unlines . map (show . solve . (read :: String -> Integer )) .  tail . lines

import Control.Monad
import Data.Int

solve :: Int64 -> Int64
solve n
  | n `mod` 2050 /= 0 = -1
  | otherwise = bitsSum $ quot n 2050
  where
    bitsSum i = sum $ read <$> (\c -> [c]) <$> show i

solveIO :: IO ()
solveIO = do
  l <- getLine
  let t = read l :: Int64
  putStr $ show (solve t) ++ "\n"

main :: IO ()
main = do
  l <- getLine
  let t = read l :: Int
  replicateM_ t solveIO

solve x ans
  | x > 0 = solve (x `div` 10) (ans + (x `mod` 10))
  | otherwise = ans

helper x =
  show $
    if y `mod` 2050 == 0
    then solve (y `div` 2050) 0
    else -1
    where
      y = read x

main = do
  getLine
  interact $ unlines . map helper . lines

solve x ans
  | x > 0 = solve (x `div` 10) (ans + (x `mod` 10))
  | otherwise = ans

helper x = show $
                if (read x :: Integer) `mod` 2050 == 0
                then solve ((read x :: Integer) `div` 2050) 0
                else -1

main = do
  getLine
  interact $ unlines . map helper . lines

module Main where

    import Control.Monad ( replicateM )

    main :: IO ()
    main = do
        input <- getLine
        let n = (read input :: Int)
        inputs <- replicateM n getLine
        let numbers = map (read::String->Int) inputs
        let ret = map getAnswer numbers
        mapM_ print ret

    getDigits:: Int -> Int
    getDigits 0 = 0
    getDigits x = xd + getDigits ((x - xd) `div` 10)
        where xd = x `mod` 10

    getAnswer:: Int -> Int
    getAnswer x
        | x `mod` 2050 == 0 = getDigits (x `div` 2050)
        | otherwise = -1

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

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

parseInteger :: C.ByteString -> Integer
parseInteger = fst . fromJust . C.readInteger

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

main :: IO ()
main = do
  [t] <- getInts
  output <- fmap mconcat $ replicateM t $ do
    n <- fmap parseInteger C.getLine
    let result = if n `mod` 2050 == 0 then solve (n `div` 2050) else (-1)
        solve 0 = 0
        solve x = x `mod` 10 + solve (x `div` 10)
    return $ integerDec result `mappend` charUtf8 '\n'
  hPutBuilder stdout output

import Control.Monad
import Data.Int
import Data.List

char2s :: Char -> [Char]
char2s c = [c]

calc :: Int64 -> Int
calc n | n `mod` 2050 == 0 =
         let k = n `div` 2050
             s = map read $ map char2s $ show k :: [Int] in
           sum s
calc _ = -1

main = do
  line <- getLine
  let t = read line :: Int
  forM_ [1..t] $ \_ -> do
    line <- getLine
    let n = read line :: Int64
    print $ calc n

import Control.Monad ( forM )

digits :: Integer -> [Integer]
digits x
    | x == 0 = [0]
    | otherwise = (x `mod` 10):digits (x `div` 10)

solve :: Integer -> Integer
solve x
    | x `mod` 2050 /= 0 = -1
    | otherwise = sum $ digits $ x `div` 2050

main :: IO ()
main = do
    a <- getLine
    let t = read a :: Int
    s <- forM [1..t] $ \_ -> do
        b <- getLine
        let n = read b :: Integer
        return (solve n) :: IO Integer
    mapM_ print s

digitSum :: Int -> Int
digitSum v
  | v /= 0 = m + d
  | otherwise = 0
  where
    m = mod v 10
    d = digitSum $ div v 10

solve :: [Int] -> [Int]
solve (val : xs)
  | m == 0 = digitSum d : next
  | otherwise = -1 : next
  where
    m = mod val 2050
    d = div val 2050
    next = solve xs
solve [] = []

main :: IO ()
main =
  interact $ to_string . solve . to_list
  where
    to_list = map read . tail . words
    to_string = unlines . map show

solve n = case foldr (\x (r,ds) -> let (q,s) = r `divMod` x in (s,q:ds)) (n,[]) $ takeWhile (<10^18) $ iterate (*10) 2050  of
    (a,_)  | a > 0 -> -1
    (_, b)         -> sum b

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

import Control.Monad

solve :: Int -> Int
solve n
  | n `mod` 2050 /= 0 = -1
  | otherwise = bitsSum $ quot n 2050
  where
    bitsSum i = sum $ read <$> (\c -> [c]) <$> show i

solveIO :: IO ()
solveIO = do
  l <- getLine
  let t = read l :: Int
  putStr $ show (solve t) ++ "\n"

main :: IO ()
main = do
  l <- getLine
  let t = read l :: Int
  replicateM_ t solveIO