Alice guesses the strings that Bob made for her.At first, Bob came up with the secret string $$$a$$$ consisting of lowercase English letters. The string $$$a$$$ has a length of $$$2$$$ or more characters. Then, from string $$$a$$$ he builds a new string $$$b$$$ and offers Alice the string $$$b$$$ so that she can guess the string $$$a$$$.Bob builds $$$b$$$ from $$$a$$$ as follows: he writes all the substrings of length $$$2$$$ of the string $$$a$$$ in the order from left to right, and then joins them in the same order into the string $$$b$$$.For example, if Bob came up with the string $$$a$$$="abac", then all the substrings of length $$$2$$$ of the string $$$a$$$ are: "ab", "ba", "ac". Therefore, the string $$$b$$$="abbaac".You are given the string $$$b$$$. Help Alice to guess the string $$$a$$$ that Bob came up with. It is guaranteed that $$$b$$$ was built according to the algorithm given above. It can be proved that the answer to the problem is unique.

The first line contains a single positive integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases in the test. Then $$$t$$$ test cases follow. Each test case consists of one line in which the string $$$b$$$ is written, consisting of lowercase English letters ($$$2 \le |b| \le 100$$$) — the string Bob came up with, where $$$|b|$$$ is the length of the string $$$b$$$. It is guaranteed that $$$b$$$ was built according to the algorithm given above.

Output $$$t$$$ answers to test cases. Each answer is the secret string $$$a$$$, consisting of lowercase English letters, that Bob came up with.

NoteThe first test case is explained in the statement.In the second test case, Bob came up with the string $$$a$$$="ac", the string $$$a$$$ has a length $$$2$$$, so the string $$$b$$$ is equal to the string $$$a$$$.In the third test case, Bob came up with the string $$$a$$$="bcdaf", substrings of length $$$2$$$ of string $$$a$$$ are: "bc", "cd", "da", "af", so the string $$$b$$$="bccddaaf".

{-# 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 = do
	t <- readInt
	mapM_ putStrLn =<< replicateM t solve

solve = do
	s <- getLine
	let
		s' = map fst $ filter snd $ zip s ( cycle [ True, False ] )
	return $ s' ++ [ last s ]

import Control.Monad

main :: IO ()
main = do
  n <- readLn
  replicateM_ n routine

routine :: IO ()
routine = do
  s <- getLine
  putStrLn $ solve s

solve :: String -> String
solve s = (head s):z
  where
    z =map fst $ filter (even.snd) $ zip s [1..]

main = do
  inputjar <- getLine
  let n = read inputjar :: Int
  solve n

solve :: Int -> IO ()
solve 0 = putStr ""
solve n = do
  input <- getLine
--   let list = read ("[" ++ map (\x -> if x == ' ' then ',' else x) input ++ "]") :: [Int]
  solveCase input
  solve (n - 1)

solveCase :: [Char] -> IO()
solveCase s = putStrLn $ [s !! i | i <- [0,2..(length s - 1)]] ++ [last s]

-- solveCase :: [Int] -> IO ()
-- solveCase (x : y : n : [])
--   | tmp <= n = print tmp
--   | otherwise = print $ tmp - x
--   where
--     tmp = n - (n `mod` x) + y

main :: IO ()
main = interact (unlines . map solve . tail . lines)

solve :: String -> String
solve (x:xs) = x : f xs
  where
    f [x] = [x]
    f (x:y:xs) = x : f xs

main = getContents >>= putStrLn . unlines . map f .  tail . lines where
    f [] = ""
    f [x,y] = [x,y]
    f (x:_:xs) = x : f xs

import Control.Monad

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

main :: IO()
main = do
    [t] <- getInts
    replicateM_ t solve

solve :: IO()
solve = do
    b <- getLine
    let c = [head b] ++ b ++ [last b]
    let n = length c
        a = [c !! i | i <- [0,2..(n-1)]]
    putStrLn a

import Control.Monad

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

main :: IO()
main = do
    [t] <- getInts
    replicateM_ t solve

solve :: IO()
solve = do
    b <- getLine
    putChar $ head b
    putStrLn $ map fst $ filter (even.snd) $ zip b [1..]

import Control.Monad

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

main :: IO()
main = do
    [t] <- getInts
    replicateM_ t routine

routine :: IO()
routine = do
    b <- getLine
    putStrLn $ solve b

solve :: String -> String
solve (h:xs) = h : (map fst $ filter (even.snd) $ zip xs [0..])
solve x = x

solve :: String -> String
solve (a:b:[]) = [a,b]
solve (a:b:xs) = [a,b]++( map snd . filter (even . fst) . zip [1..] . init $ xs) ++ [(last xs)]

solveCase :: Int -> IO()
solveCase 0 = return ()
solveCase t = do
  test <- getLine
  putStrLn . solve  $ test
  solveCase (t-1)

getInt :: IO Int
getInt = fmap read getLine

main :: IO()
main = do
  n <- getInt
  solveCase n

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

process [x,y] = x:y:[]
process (a:b:c) = a: (process c)

main = do
		n<- read <$> getLine ::IO Int
		k<-replicateM n getLine
		mapM_ putStrLn $ map process k

import Control.Monad

getStr :: String -> String
getStr (a:b:[]) = [a, b]
getStr (a:_:l@(c:_)) = a : getStr l
getStr [] = []

main = do
  n <- read <$> getLine
  a <- (replicateM n getLine)
  mapM_ putStrLn (getStr <$> a)

solve :: String -> String
solve (a:b:[]) = [a,b]
solve (a:b:xs) = [a,b]++( map snd . filter (even . fst) . zip [1..] . init $ xs) ++ [(last xs)]

solveCase :: Int -> IO()
solveCase 0 = return ()
solveCase t = do
  test <- getLine
  putStrLn . show . solve  $ test
  solveCase (t-1)

getInt :: IO Int
getInt = fmap read getLine

main :: IO()
main = do
  n <- getInt
  solveCase n


You are given a chessboard of size $$$n \times n$$$. It is filled with numbers from $$$1$$$ to $$$n^2$$$ in the following way: the first $$$\lceil \frac{n^2}{2} \rceil$$$ numbers from $$$1$$$ to $$$\lceil \frac{n^2}{2} \rceil$$$ are written in the cells with even sum of coordinates from left to right from top to bottom. The rest $$$n^2 - \lceil \frac{n^2}{2} \rceil$$$ numbers from $$$\lceil \frac{n^2}{2} \rceil + 1$$$ to $$$n^2$$$ are written in the cells with odd sum of coordinates from left to right from top to bottom. The operation $$$\lceil\frac{x}{y}\rceil$$$ means division $$$x$$$ by $$$y$$$ rounded up.For example, the left board on the following picture is the chessboard which is given for $$$n=4$$$ and the right board is the chessboard which is given for $$$n=5$$$.  You are given $$$q$$$ queries. The $$$i$$$-th query is described as a pair $$$x_i, y_i$$$. The answer to the $$$i$$$-th query is the number written in the cell $$$x_i, y_i$$$ ($$$x_i$$$ is the row, $$$y_i$$$ is the column). Rows and columns are numbered from $$$1$$$ to $$$n$$$.

The first line contains two integers $$$n$$$ and $$$q$$$ ($$$1 \le n \le 10^9$$$, $$$1 \le q \le 10^5$$$) — the size of the board and the number of queries. The next $$$q$$$ lines contain two integers each. The $$$i$$$-th line contains two integers $$$x_i, y_i$$$ ($$$1 \le x_i, y_i \le n$$$) — description of the $$$i$$$-th query.

For each query from $$$1$$$ to $$$q$$$ print the answer to this query. The answer to the $$$i$$$-th query is the number written in the cell $$$x_i, y_i$$$ ($$$x_i$$$ is the row, $$$y_i$$$ is the column). Rows and columns are numbered from $$$1$$$ to $$$n$$$. Queries are numbered from $$$1$$$ to $$$q$$$ in order of the input.

NoteAnswers to the queries from examples are on the board in the picture from the problem statement.

import qualified Data.ByteString.Char8 as B
import Data.Maybe

num n [x,y] =
    let z = (x-1)*n+(y-1)
        q = (z `div` 2) + 1
        r = ((n*n+(if even n then 0 else 1))`div`2)
    in if even x
        then q +
            if odd z
                then if odd n then r else 0
                else if odd n then 0 else r
        else q + if odd z then r else 0

int = fst . fromJust . B.readInteger
ints = map int . B.words

main = do
     [n,k] <-  ints <$> B.getLine
     B.interact $ B.unlines . map ( B.pack .  show . (num n) . ints ) . B.lines

import qualified Data.ByteString.Char8 as B
import Data.Maybe

num n [x,y] =
    let z = (x-1)*n+(y-1)
        q = (z `div` 2) + 1
        r = ((n*n+(if even n then 0 else 1))`div`2)
    in if even x
        then if odd z
            then q + if odd n then r else 0
            else q + if odd n then 0 else r
        else q + if even z then 0 else r

int = fst . fromJust . B.readInteger
ints = map int . B.words

main = do
     [n,k] <-  ints <$> B.getLine
     B.interact $ B.unlines . map ( B.pack .  show . (num n) . ints ) . B.lines

import qualified Data.ByteString.Char8 as B
import Data.Maybe

num n [x,y] =
    let z = (x-1)*n+(y-1) in
    if even x
        then if odd z
            then if odd n then ((n*n+1)`div`2) + (z `div` 2) + 1  else (z `div` 2) + 1
            else if odd n then (z `div` 2) + 1 else ((n*n+(if even n then 0 else 1))`div`2) + z `div` 2 + 1
        else if even z
            then (z `div` 2) + 1
            else ((n*n+(if even n then 0 else 1))`div`2) + z `div` 2 + 1

int = fst . fromJust . B.readInteger
ints = map int . B.words

main = do
     [n,k] <-  ints <$> B.getLine
     B.interact $ B.unlines . map ( B.pack .  show . (num n) . ints ) . B.lines

import qualified Data.ByteString.Char8 as B
import Data.Maybe

num n [x,y] =
    let z = (x-1)*n+(y-1) in
    if even x
        then if odd z
            then (z `div` 2) + 1
            else (n*n`div`2) + z `div` 2 + 1
        else if even z
            then (z `div` 2) + 1
            else (n*n`div`2) + z `div` 2 + 1

int = fst . fromJust . B.readInt
ints = map int . B.words

main = do
     [n,k] <-  ints <$> B.getLine
     B.interact $ B.unlines . map ( B.pack .  show . (num n) . ints ) . B.lines

{-

4 5
1 1
4 4
4 3
3 2
2 4

-}

import qualified Data.ByteString.Char8 as B
import Data.Maybe

num n [x,y] =
    let z = (x-1)*n+(y-1) in
    if even x
        then if odd z
            then if odd n then ((n*n+1)`div`2) + (z `div` 2) + 1  else (z `div` 2) + 1
            else if odd n then (z `div` 2) + 1 else ((n*n+(if even n then 0 else 1))`div`2) + z `div` 2 + 1
        else if even z
            then (z `div` 2) + 1
            else ((n*n+(if even n then 0 else 1))`div`2) + z `div` 2 + 1

int = fst . fromJust . B.readInt
ints = map int . B.words

main = do
     [n,k] <-  ints <$> B.getLine
     B.interact $ B.unlines . map ( B.pack .  show . (num n) . ints ) . B.lines


Serval soon said goodbye to Japari kindergarten, and began his life in Japari Primary School.In his favorite math class, the teacher taught him the following interesting definitions.A parenthesis sequence is a string, containing only characters "(" and ")".A correct parenthesis sequence is a parenthesis sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, parenthesis sequences "()()", "(())" are correct (the resulting expressions are: "(1+1)+(1+1)", "((1+1)+1)"), while ")(" and ")" are not. Note that the empty string is a correct parenthesis sequence by definition.We define that $$$|s|$$$ as the length of string $$$s$$$. A strict prefix $$$s[1\dots l]$$$ $$$(1\leq l< |s|)$$$ of a string $$$s = s_1s_2\dots s_{|s|}$$$ is string $$$s_1s_2\dots s_l$$$. Note that the empty string and the whole string are not strict prefixes of any string by the definition.Having learned these definitions, he comes up with a new problem. He writes down a string $$$s$$$ containing only characters "(", ")" and "?". And what he is going to do, is to replace each of the "?" in $$$s$$$ independently by one of "(" and ")" to make all strict prefixes of the new sequence not a correct parenthesis sequence, while the new sequence should be a correct parenthesis sequence.After all, he is just a primary school student so this problem is too hard for him to solve. As his best friend, can you help him to replace the question marks? If there are many solutions, any of them is acceptable.

The first line contains a single integer $$$|s|$$$ ($$$1\leq |s|\leq 3 \cdot 10^5$$$), the length of the string. The second line contains a string $$$s$$$, containing only "(", ")" and "?".

A single line contains a string representing the answer. If there are many solutions, any of them is acceptable. If there is no answer, print a single line containing ":(" (without the quotes).

NoteIt can be proved that there is no solution for the second sample, so print ":(".

{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE Safe #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE ExplicitForAll #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE NoMonomorphismRestriction #-}

import Data.Bits
import Data.List
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as BSL
import Data.IntMap.Strict (IntMap)
import qualified Data.IntMap.Strict as IM
import Data.IntSet (IntSet)
import qualified Data.IntSet as IS
import qualified Data.Array.IArray as A
import qualified Data.Array.MArray.Safe as A
-- import qualified Data.Array.MArray as A
import Data.Array (Array)
import Data.Array.Unboxed (UArray)
import Data.Array.IArray (IArray)
import Data.Array.MArray.Safe (MArray)
import Data.Array.IO.Safe (IOArray, IOUArray)
import Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)
{-
import qualified Data.Vector.Unboxed as VU
import qualified Data.Vector.Unboxed.Mutable as VUM
-}
import Control.Monad
import Control.Monad.ST
import Control.Monad.ST.Lazy (strictToLazyST, lazyToStrictST)
import qualified Control.Monad.ST.Lazy as STL
-- import Control.Monad.ST
import Control.Applicative
import Data.Maybe
import Data.Tuple
import Data.Ord
import Control.Monad.State.Strict
import Data.Int
import Data.Word
import Data.STRef
import Data.IORef
import Data.Function
import System.IO
import System.Exit
import Data.Char

main :: IO ()
main = do
  n <- readInt <$> getLine
  s <- BS.takeWhile (>='!') . BS.dropWhile (<'!') <$> BS.getLine
  let opens = BS.count '(' s
      closes = BS.count ')' s
      opensleft = shiftR n 1 - opens
      closesleft = shiftR n 1 - closes
  if odd n || opensleft < 0 || closesleft < 0 then putStrLn ":(" else do
  let (!ol_,res) = BS.mapAccumL
        (\ !ol c -> if | c /= '?' -> (ol,c)
                       | ol > 0 -> (ol-1,'(')
                       | otherwise -> (0,')')) opensleft s
  if test res then BS.putStrLn res else putStrLn ":("

test :: BS.ByteString -> Bool
test bs
  | BS.null bs        = True
  | BS.head bs == '(' = loop (1::Int) (BS.tail bs)
  | otherwise         = False
  where
    loop 0 bs | BS.null bs = True
              | otherwise  = False
    loop !lv bs = case BS.uncons bs of
      Nothing        -> False
      Just ('(',bs0) -> loop (lv+1) bs0
      Just (')',bs0) -> loop (lv-1) bs0
      _              -> False

rInt :: StateT BSL.ByteString Maybe Int
rInt = StateT $ BSL.readInt . BSL.dropWhile (<'!')
rIntS :: StateT BS.ByteString Maybe Int
rIntS = StateT $ BS.readInt . BS.dropWhile (<'!')

#define D(f,r,d) f::Integral a=>a->d;f=fromIntegral;r::String->d;r=read
#define C(f,r,g,h,d) D(f,r,d);g,h::RealFrac a=>a->d;g=floor;h=ceiling
C(_toInteger_,readInteger,floorInteger,ceilInteger,Integer)
C(toInt,readInt,floorInt,ceilInt,Int)
C(toI8,readI8,floorI8,ceilI8,Int8)
C(toI16,readI16,floorI16,ceilI16,Int16)
C(toI32,readI32,floorI32,ceilI32,Int32)
C(toI64,readI64,floorI64,ceilI64,Int64)
C(toWord,readWord,floorWord,ceilWord,Word)
C(toW8,readW8,floorW8,ceilW8,Word8)
C(toW16,readW16,floorW16,ceilW16,Word16)
C(toW32,readW32,floorW32,ceilW32,Word32)
C(toW64,readW64,floorW64,ceilW64,Word64)
D(toDouble,readDouble,Double)
D(toFloat,readFloat,Float)
#undef D
#undef C

{-# INLINE wrA #-}
wrA = A.writeArray
{-# INLINE rdA #-}
rdA = A.readArray
{-# INLINE mdA #-}
mdA arr f i = do
  ai <- rdA arr i
  let fai = f ai
  wrA arr i fai
  return (ai,fai)
{-# INLINE mdA' #-}
mdA' arr f i = do
  !ai <- rdA arr i
  let !fai = f ai
  wrA arr i fai
  return (ai,fai)
{-# INLINE swapA #-}
swapA arr i j = do
  ai <- rdA arr i
  wrA arr i =<< rdA arr j
  wrA arr j ai

#define N(f,g,a,m)\
  f :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> e -> m (a i e); f=A.newArray;\
  g :: forall e i s. (C(a,m)A.Ix i) => (i,i) -> m (a i e); g=A.newArray_
#define C(a,m)
N(newIOA,newIOA_,IOArray,IO)
N(newSTA,newSTA_,STArray s,ST s)
#undef C
#define C(a,m) MArray (a) e (m),
N(newIOUA,newIOUA_,IOUArray,IO)
N(newSTUA,newSTUA_,STUArray s,ST s)
#undef C
#undef N


You have a sequence $$$a$$$ with $$$n$$$ elements $$$1, 2, 3, \dots, k - 1, k, k - 1, k - 2, \dots, k - (n - k)$$$ ($$$k \le n < 2k$$$).Let's call as inversion in $$$a$$$ a pair of indices $$$i < j$$$ such that $$$a[i] > a[j]$$$.Suppose, you have some permutation $$$p$$$ of size $$$k$$$ and you build a sequence $$$b$$$ of size $$$n$$$ in the following manner: $$$b[i] = p[a[i]]$$$.Your goal is to find such permutation $$$p$$$ that the total number of inversions in $$$b$$$ doesn't exceed the total number of inversions in $$$a$$$, and $$$b$$$ is lexicographically maximum.Small reminder: the sequence of $$$k$$$ integers is called a permutation if it contains all integers from $$$1$$$ to $$$k$$$ exactly once.Another small reminder: a sequence $$$s$$$ is lexicographically smaller than another sequence $$$t$$$, if either $$$s$$$ is a prefix of $$$t$$$, or for the first $$$i$$$ such that $$$s_i \ne t_i$$$, $$$s_i < t_i$$$ holds (in the first position that these sequences are different, $$$s$$$ has smaller number than $$$t$$$).

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. The first and only line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$k \le n < 2k$$$; $$$1 \le k \le 10^5$$$) — the length of the sequence $$$a$$$ and its maximum. It's guaranteed that the total sum of $$$k$$$ over test cases doesn't exceed $$$10^5$$$.

For each test case, print $$$k$$$ integers — the permutation $$$p$$$ which maximizes $$$b$$$ lexicographically without increasing the total number of inversions. It can be proven that $$$p$$$ exists and is unique.

NoteIn the first test case, the sequence $$$a = [1]$$$, there is only one permutation $$$p = [1]$$$.In the second test case, the sequence $$$a = [1, 2]$$$. There is no inversion in $$$a$$$, so there is only one permutation $$$p = [1, 2]$$$ which doesn't increase the number of inversions.In the third test case, $$$a = [1, 2, 1]$$$ and has $$$1$$$ inversion. If we use $$$p = [2, 1]$$$, then $$$b = [p[a[1]], p[a[2]], p[a[3]]] = [2, 1, 2]$$$ and also has $$$1$$$ inversion.In the fourth test case, $$$a = [1, 2, 3, 2]$$$, and since $$$p = [1, 3, 2]$$$ then $$$b = [1, 3, 2, 3]$$$. Both $$$a$$$ and $$$b$$$ have $$$1$$$ inversion and $$$b$$$ is the lexicographically maximum.

{-# LANGUAGE DeriveFunctor       #-}
{-# LANGUAGE GADTs               #-}
{-# LANGUAGE OverloadedStrings   #-}
{-# LANGUAGE Safe                #-}
{-# 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.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)

solve :: Int -> Int -> [Int]
solve n k = p
    where
        initialP = [1 .. k]
        reverseSuffixLength = n - k + 1
        stayPrefixLength = k - reverseSuffixLength
        (prefix, suffix) = splitAt stayPrefixLength initialP
        p = prefix ++ reverse suffix

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


There are three sticks with integer lengths $$$l_1, l_2$$$ and $$$l_3$$$.You are asked to break exactly one of them into two pieces in such a way that:   both pieces have positive (strictly greater than $$$0$$$) integer length;  the total length of the pieces is equal to the original length of the stick;  it's possible to construct a rectangle from the resulting four sticks such that each stick is used as exactly one of its sides. A square is also considered a rectangle.Determine if it's possible to do that.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. The only line of each testcase contains three integers $$$l_1, l_2, l_3$$$ ($$$1 \le l_i \le 10^8$$$) — the lengths of the sticks.

For each testcase, print "YES" if it's possible to break one of the sticks into two pieces with positive integer length in such a way that it's possible to construct a rectangle from the resulting four sticks. Otherwise, print "NO". You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as a positive answer).

NoteIn the first testcase, the first stick can be broken into parts of length $$$1$$$ and $$$5$$$. We can construct a rectangle with opposite sides of length $$$1$$$ and $$$5$$$.In the second testcase, breaking the stick of length $$$2$$$ can only result in sticks of lengths $$$1, 1, 2, 5$$$, which can't be made into a rectangle. Breaking the stick of length $$$5$$$ can produce results $$$2, 3$$$ or $$$1, 4$$$ but neither of them can't be put into a rectangle.In the third testcase, the second stick can be broken into parts of length $$$2$$$ and $$$2$$$. The resulting rectangle has opposite sides $$$2$$$ and $$$2$$$ (which is a square).In the fourth testcase, the third stick can be broken into parts of length $$$2$$$ and $$$2$$$. The resulting rectangle has opposite sides $$$2$$$ and $$$5$$$.

module Main where

import Data.List
import Control.Monad (guard, replicateM)

sum2is3 :: [Int] -> Bool
sum2is3 xs =
  f sortedXs || f (reverse sortedXs)
 where
  sortedXs = sort xs
  f sl = sum (take 2 sl) == last sl

maySplit :: [Int] -> Bool
maySplit xs =
  x1 == x2 || x2 == x3
 where
  sxs = sort xs
  (x1, x2, x3) = (sxs !! 0, sxs !! 1, sxs !! 2)

solve :: [Int] -> String
solve xs
  | odd (sum xs) = "NO"
  | sum2is3 xs = "YES"
  | otherwise = if maySplit xs then "YES" else "NO"
 where
  rs = reverse $ sort xs

readLineInts :: IO [Int]
readLineInts = do
  inputs <- words <$> getLine
  pure $ read <$> inputs

getInt = read <$> getLine

main :: IO ()
main = do
  t <- getInt
  ints <- replicateM t readLineInts
  let solutions = solve <$> ints
  mapM_ putStrLn solutions

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

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

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

possible :: ([Int]->Bool)
possible (a:b:c:[]) = (a==b && c`mod`2==0) || (b-a==c)

main :: IO ()
main = do
    [t] <- readInts
    replicateM_ t $ do
        ar <- readInts
        putStrLn $ if any possible $ permutations ar then "YES" else "NO"

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

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

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

possible :: ([Int]->Bool)
possible (a:b:c:[]) = (a==b && c`mod`2==0) || (b-a==c)

main :: IO ()
main = do
    [t] <- readInts
    replicateM_ t $ do
        [a,b,c] <- readInts
        putStrLn $ if any possible (permutations [a,b,c]) then "YES" else "NO"

module Main where

import Control.Monad (replicateM)
import Data.List

solve :: [Int] -> String
solve xs
  | sum (tail rs) == head rs = "YES"
  | even (last rs) && rs !! 0 == rs !! 1 = "YES"
  | otherwise = "NO"
 where
  rs = reverse $ sort xs

readLineInts :: IO [Int]
readLineInts = do
  inputs <- words <$> getLine
  pure $ read <$> inputs

getInt = read <$> getLine

main :: IO ()
main = do
  t <- getInt
  ints <- replicateM t readLineInts
  let solutions = solve <$> ints
  mapM_ putStrLn solutions


There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads.Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them. When the horse reaches a city (including the first one), it goes to one of the cities connected to the current city. But it is a strange horse, it only goes to cities in which they weren't before. In each such city, the horse goes with equal probabilities and it stops when there are no such cities. Let the length of each road be 1. The journey starts in the city 1. What is the expected length (expected value of length) of their journey? You can read about expected (average) value by the link https://en.wikipedia.org/wiki/Expected_value.

The first line contains a single integer n (1 ≤ n ≤ 100000) — number of cities. Then n - 1 lines follow. The i-th line of these lines contains two integers ui and vi (1 ≤ ui, vi ≤ n, ui ≠ vi) — the cities connected by the i-th road. It is guaranteed that one can reach any city from any other by the roads.

Print a number — the expected length of their journey. The journey starts in the city 1. Your answer will be considered correct if its absolute or relative error does not exceed 10 - 6. Namely: let's assume that your answer is a, and the answer of the jury is b. The checker program will consider your answer correct, if .

NoteIn the first sample, their journey may end in cities 3 or 4 with equal probability. The distance to city 3 is 1 and to city 4 is 2, so the expected length is 1.5.In the second sample, their journey may end in city 4 or 5. The distance to the both cities is 2, so the expected length is 2.

{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -funfolding-use-threshold=16 -fexcess-precision -funbox-strict-fields #-}
module Main where
import qualified Data.ByteString.Lazy.Char8 as B
import Control.Monad
import Control.Monad.Trans.State.Lazy
import Data.Array

main = B.getContents >>= print . evalState app . B.words

app = do
  n <- poi
  g <- fmap (accumArray (flip (:)) [] (1, n) . concat) $ replicateM (n - 1) $ liftM2 (\u v -> [(u, v), (v, u)]) poi poi
  return $ solve g
  where
    pop = state $ \(x:xs) -> (x, xs)
    poi = fmap int pop
    int = maybe undefined fst . B.readInt

solve = dfs (\_ cs -> if null cs then 0 else let d = fromIntegral $ length cs in sum cs / d + 1)

dfs f g = go 0 1
  where go p u = f u $ map (go u) $ filter (/= p) (g!u)


Dima, Inna and Seryozha have gathered in a room. That's right, someone's got to go. To cheer Seryozha up and inspire him to have a walk, Inna decided to cook something. Dima and Seryozha have n fruits in the fridge. Each fruit has two parameters: the taste and the number of calories. Inna decided to make a fruit salad, so she wants to take some fruits from the fridge for it. Inna follows a certain principle as she chooses the fruits: the total taste to the total calories ratio of the chosen fruits must equal k. In other words,  , where aj is the taste of the j-th chosen fruit and bj is its calories.Inna hasn't chosen the fruits yet, she is thinking: what is the maximum taste of the chosen fruits if she strictly follows her principle? Help Inna solve this culinary problem — now the happiness of a young couple is in your hands!Inna loves Dima very much so she wants to make the salad from at least one fruit.

The first line of the input contains two integers n, k (1 ≤ n ≤ 100, 1 ≤ k ≤ 10). The second line of the input contains n integers a1, a2, ..., an (1 ≤ ai ≤ 100) — the fruits' tastes. The third line of the input contains n integers b1, b2, ..., bn (1 ≤ bi ≤ 100) — the fruits' calories. Fruit number i has taste ai and calories bi.

If there is no way Inna can choose the fruits for the salad, print in the single line number -1. Otherwise, print a single integer — the maximum possible sum of the taste values of the chosen fruits.

NoteIn the first test sample we can get the total taste of the fruits equal to 18 if we choose fruit number 1 and fruit number 2, then the total calories will equal 9. The condition  fulfills, that's exactly what Inna wants.In the second test sample we cannot choose the fruits so as to follow Inna's principle.

--import qualified Data.Map as Map
import qualified Data.Map.Strict as Map
--import qualified Data.HashMap.Strict as Map

readInts :: String -> [Int]
readInts = map read . words

addFruit (balance, taste) balanceToMaxTaste = Map.unionWith max balanceToMaxTaste $
    Map.map ((+) taste) $ Map.mapKeysMonotonic ((+) balance) balanceToMaxTaste
--  Map.fromList $ map (\(b, t) -> (balance + b, taste + t)) $ Map.toList balanceToMaxTaste

solve [n,k] as bs = if maxTaste > 0 then maxTaste else -1
    where maxTaste = (Map.!) maxTastes 0
          maxTastes = foldr addFruit (Map.singleton 0 0) balanceTastes
          balanceTastes = [(a - b*k, a) | (a, b) <- zip as bs]

main = do
    nk <- getLine
    as <- getLine
    bs <- getLine
    print $ solve (readInts nk) (readInts as) (readInts bs)


A ski base is planned to be built in Walrusland. Recently, however, the project is still in the constructing phase. A large land lot was chosen for the construction. It contains n ski junctions, numbered from 1 to n. Initially the junctions aren't connected in any way.In the constructing process m bidirectional ski roads will be built. The roads are built one after another: first the road number 1 will be built, then the road number 2, and so on. The i-th road connects the junctions with numbers ai and bi.Track is the route with the following properties:  The route is closed, that is, it begins and ends in one and the same junction. The route contains at least one road.  The route doesn't go on one road more than once, however it can visit any junction any number of times. Let's consider the ski base as a non-empty set of roads that can be divided into one or more tracks so that exactly one track went along each road of the chosen set. Besides, each track can consist only of roads from the chosen set. Ski base doesn't have to be connected.Two ski bases are considered different if they consist of different road sets.After building each new road the Walrusland government wants to know the number of variants of choosing a ski base based on some subset of the already built roads. The government asks you to help them solve the given problem.

The first line contains two integers n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ 105). They represent the number of junctions and the number of roads correspondingly. Then on m lines follows the description of the roads in the order in which they were built. Each road is described by a pair of integers ai and bi (1 ≤ ai, bi ≤ n, ai ≠ bi) — the numbers of the connected junctions. There could be more than one road between a pair of junctions.

Print m lines: the i-th line should represent the number of ways to build a ski base after the end of construction of the road number i. The numbers should be printed modulo 1000000009 (109 + 9).

NoteLet us have 3 junctions and 4 roads between the junctions have already been built (as after building all the roads in the sample): 1 and 3, 2 and 3, 2 roads between junctions 1 and 2. The land lot for the construction will look like this:   The land lot for the construction will look in the following way:   We can choose a subset of roads in three ways:   In the first and the second ways you can choose one path, for example, 1 - 2 - 3 - 1. In the first case you can choose one path 1 - 2 - 1.

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

import Control.Monad.ST
import Data.Array.ST
import Data.STRef

parseInput = do
    n <- readInt
    m <- readInt
    edges <- replicateM m ((,) <$> readInt <*> readInt)
    return (n, edges)
  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

modulo :: Int
modulo = 1000000009

newtype ModP = ModP Int deriving Eq

instance Num ModP where
    ModP a + ModP b = ModP $ (a + b) `mod` modulo
    ModP a - ModP b = ModP $ (a - b) `mod` modulo
    ModP a * ModP b = ModP $ (a * b) `mod` modulo
    fromInteger = ModP . fromInteger
    signum = undefined
    abs = undefined

instance Show ModP where
    show (ModP a) = show a

solve :: (Int, [(Int, Int)]) -> ByteString
solve (n, edges) = BS.unlines . map (BS.pack . show . (\x -> x-1)) $ runST stMonad
  where
    stMonad :: ST s [ModP]
    stMonad = do
        uf <- buildUF (1, n) :: ST s (UnionFind s)
        eqs <- newSTRef 1 :: ST s (STRef s ModP)
        mapM (solveEdge uf eqs) edges

solveEdge :: UnionFind s -> STRef s ModP -> (Int, Int) -> ST s ModP
solveEdge uf eqs (a, b) = do
    merged <- mergeUF uf a b
    unless merged $ modifySTRef eqs (*2)
    readSTRef eqs

type UnionFind s = STUArray s Int Int

buildUF :: (Int, Int) -> ST s (UnionFind s)
buildUF bnds = newArray bnds (-1)

findUF :: UnionFind s -> Int -> ST s Int
findUF uf a = do
    fa <- readArray uf a
    if fa == -1
      then return a
      else do
        ret <- findUF uf fa
        writeArray uf a ret
        return ret

mergeUF :: UnionFind s -> Int -> Int -> ST s Bool
mergeUF uf a b = do
    fa <- findUF uf a
    fb <- findUF uf b
    if fa == fb
      then return False
      else do
        writeArray uf fa fb
        return True

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

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


You are given two arrays of integers $$$a_1, a_2, \ldots, a_n$$$ and $$$b_1, b_2, \ldots, b_n$$$.Let's define a transformation of the array $$$a$$$:  Choose any non-negative integer $$$k$$$ such that $$$0 \le k \le n$$$.  Choose $$$k$$$ distinct array indices $$$1 \le i_1 < i_2 < \ldots < i_k \le n$$$.  Add $$$1$$$ to each of $$$a_{i_1}, a_{i_2}, \ldots, a_{i_k}$$$, all other elements of array $$$a$$$ remain unchanged.  Permute the elements of array $$$a$$$ in any order. Is it possible to perform some transformation of the array $$$a$$$ exactly once, so that the resulting array is equal to $$$b$$$?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Descriptions of test cases follow. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$) — the size of arrays $$$a$$$ and $$$b$$$. The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$-100 \le a_i \le 100$$$). The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$-100 \le b_i \le 100$$$).

For each test case, print "YES" (without quotes) if it is possible to perform a transformation of the array $$$a$$$, so that the resulting array is equal to $$$b$$$. Print "NO" (without quotes) otherwise. You can print each letter in any case (upper or lower).

NoteIn the first test case, we can make the following transformation:  Choose $$$k = 2$$$.  Choose $$$i_1 = 1$$$, $$$i_2 = 2$$$.  Add $$$1$$$ to $$$a_1$$$ and $$$a_2$$$. The resulting array is $$$[0, 2, 0]$$$.  Swap the elements on the second and third positions. In the second test case there is no suitable transformation.In the third test case we choose $$$k = 0$$$ and do not change the order of elements.

import qualified Control.Monad as CM
import qualified Data.List as DL

solve :: IO ()
solve = do
  getLine
  asu <- readv
  bsu <- readv
  let
    [as,bs] = DL.sort <$> [asu,bsu]
    diffs = zipWith subtract as bs
    ans = if all (\x->x==0||x==1) diffs then "YES" else "NO"
  putStrLn ans

printv :: Show a => [a] -> IO ()
printv xs =  putStrLn $ unwords $ fmap show xs

readv :: Read a => IO [a]
readv = fmap read . words <$> getLine

main :: IO ()
main = do
  ~[n] <- readv
  CM.replicateM_ n solve

import Data.List (sort)

main :: IO ()
main = interact processInput

processInput :: String -> String
processInput input = unlines $ processLines $ drop 1 $ lines input

processLines :: [String] -> [String]
processLines (n_line:a_line:b_line:other_lines)
    = processTest (a_line, b_line) : processLines other_lines
processLines _ = []

processTest :: (String, String) -> String
processTest (a_line, b_line) = output
    where
        a_seq = map read $ words a_line
        b_seq = map read $ words b_line
        output = if canMakeEqual a_seq b_seq then "YES" else "NO"

canMakeEqual :: [Integer] -> [Integer] -> Bool
canMakeEqual current_sequence target_sequence = result
    where
        result = all (`elem` [0, 1]) [tx - x | (x, tx) <- zip (sort current_sequence) (sort target_sequence)]


You are given a string $$$s$$$. You need to find two non-empty strings $$$a$$$ and $$$b$$$ such that the following conditions are satisfied:  Strings $$$a$$$ and $$$b$$$ are both subsequences of $$$s$$$.  For each index $$$i$$$, character $$$s_i$$$ of string $$$s$$$ must belong to exactly one of strings $$$a$$$ or $$$b$$$.  String $$$a$$$ is lexicographically minimum possible; string $$$b$$$ may be any possible string. Given string $$$s$$$, print any valid $$$a$$$ and $$$b$$$.Reminder:A string $$$a$$$ ($$$b$$$) is a subsequence of a string $$$s$$$ if $$$a$$$ ($$$b$$$) can be obtained from $$$s$$$ by deletion of several (possibly, zero) elements. For example, "dores", "cf", and "for" are subsequences of "codeforces", while "decor" and "fork" are not.A string $$$x$$$ is lexicographically smaller than a string $$$y$$$ if and only if one of the following holds:  $$$x$$$ is a prefix of $$$y$$$, but $$$x \ne y$$$;  in the first position where $$$x$$$ and $$$y$$$ differ, the string $$$x$$$ has a letter that appears earlier in the alphabet than the corresponding letter in $$$y$$$.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 1000$$$). Description of the test cases follows. The first and only line of each test case contains one string $$$s$$$ ($$$2 \le |s| \le 100$$$ where $$$|s|$$$ means the length of $$$s$$$). String $$$s$$$ consists of lowercase Latin letters.

For each test case, print the strings $$$a$$$ and $$$b$$$ that satisfy the given conditions. If there are multiple answers, print any.

NoteIn the first test case, there are only two choices: either $$$a =$$$ f and $$$b = $$$ c or $$$a = $$$ c and $$$b = $$$ f. And $$$a = $$$c is lexicographically smaller than $$$a = $$$ f.In the second test case, a is the only character in the string.In the third test case, it can be proven that b is the lexicographically smallest subsequence of $$$s$$$. The second string can be of two variants; one of them is given here.

import Control.Monad (forM_)
import Data.List (sort)

main = do
  n <- read <$> getLine
  forM_ [1 .. n] $ \_ -> do
    line <- getLine
    let x = minimum line
    let xs = let (a, _ : b) = span (/= x) line in a ++ b
    putStrLn $ x : ' ' : xs

{-# LANGUAGE Safe #-}
{-# OPTIONS_GHC -O2 #-}

import qualified Control.Monad as CM
import qualified Data.List as DL
import System.IO

solve :: IO ()
solve = do
  cs <- getLine
  let
    x = DL.minimum cs
    y = DL.delete x cs
  putStrLn $ x:" " ++ y

printv :: Show a => [a] -> IO ()
printv xs =  putStrLn $ unwords $ fmap show xs

readv :: Read a => IO [a]
readv = fmap read . words <$> getLine

main :: IO ()
main = do
  ~[n] <- readv
  CM.replicateM_ n solve

import Control.Monad
import Data.Foldable (traverse_)
import Data.List

pickSmallest :: String -> (Char, String)
pickSmallest s =
    let min_char = minimum s
        remain = delete min_char s
     in (min_char, remain)

output :: (Char, String) -> IO ()
output (c, s) = putStrLn $ [c] ++ " " ++ s

main :: IO ()
main = do
    no_of_input <- getLine
    inputs <- replicateM (read no_of_input) getLine
    let ans = map pickSmallest inputs
    traverse_ (output) ans

import Control.Arrow ((>>>))
import Data.List

main :: IO ()
main = interact $ lines >>> drop 1 >>> map solve >>> unlines

solve s = let c = minimum s in c : ' ' : delete c s

import Control.Monad (forM_)
import Data.List (sort)

main = do
  n <- read <$> getLine
  forM_ [1 .. n] $ \_ -> do
    (x : xs) <- sort <$> getLine
    putStrLn $ x : ' ' : xs


Polycarp has a poor memory. Each day he can remember no more than $$$3$$$ of different letters. Polycarp wants to write a non-empty string of $$$s$$$ consisting of lowercase Latin letters, taking minimum number of days. In how many days will he be able to do it?Polycarp initially has an empty string and can only add characters to the end of that string.For example, if Polycarp wants to write the string lollipops, he will do it in $$$2$$$ days:   on the first day Polycarp will memorize the letters l, o, i and write lolli;  On the second day Polycarp will remember the letters p, o, s, add pops to the resulting line and get the line lollipops. If Polycarp wants to write the string stringology, he will do it in $$$4$$$ days:   in the first day will be written part str;  on day two will be written part ing;  on the third day, part of olog will be written;  on the fourth day, part of y will be written. For a given string $$$s$$$, print the minimum number of days it will take Polycarp to write it.

The first line of input data contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Each test case consists of a non-empty string $$$s$$$ consisting of lowercase Latin letters (the length of the string $$$s$$$ does not exceed $$$2 \cdot 10^5$$$) — the string Polycarp wants to construct. It is guaranteed that the sum of string lengths $$$s$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, print a single number — minimum number of days it will take Polycarp to write the string $$$s$$$ from memory.

6

lollipops

stringology

abracadabra

codeforces

test

f

--
-- Michael V. Antosha
-- 2022
-- Michael.Antosha@gmail.com
--

{-# LANGUAGE Safe                #-}
{-# LANGUAGE ImportQualifiedPost #-}

{-# language NoMonomorphismRestriction #-}

{-# options_ghc -O3                              #-}

{-# options_ghc -Weverything                     #-}
{-# options_ghc -Werror                          #-}

{-# options_ghc -Wno-safe                        #-}     -- no warning if inferred as safe
{-# options_ghc -Wno-all-missed-specialisations  #-}     -- "Could not specialise..." when -O1
{-# options_ghc -Wno-missing-import-lists        #-}
{-# options_ghc -Wno-missing-local-signatures    #-}

import Prelude               hiding (getLine)
import System.IO
import Control.Arrow
import Control.Monad
import Data.ByteString.Char8 qualified as B
import Data.Char
import Data.List             qualified as L

ri = readInts <$> B.getLine :: IO [Int]
  where
    readInts  = L.unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace
    dropSpace = B.dropWhile isSpace

main :: IO ()
main = do
    [t] <- ri
    tcs <- replicateM t getLine
    mapM_ (putStrLn.show.solve) tcs

solve ins = f ins :: Int
  where
    f [] = 0
    f s  = 1 + f rest
      where
        ltrs = take 3 . L.nub $ s
        rest = dropWhile (`elem` ltrs) s

module Main where

import Data.List
import Data.Maybe
import qualified Data.Map.Strict as Map

main = do
  tStr <- getLine
  let t = read tStr :: Int
  input <- getContents
  let sols = map (format . solve . parse) $ take t $ sep $ lines input
  mapM_ putStrLn sols

sep = id

parse = id

format = show

solve :: String -> Int
solve xs = length $ takeWhile (/= "") $ iterate afterOneDay xs

afterOneDay xs = afterOneDay' [] xs

afterOneDay' _ "" = ""
afterOneDay' ys (x:xs)
  | x `elem` ys = afterOneDay' ys xs
  | length ys < 3 = afterOneDay' (x:ys) xs
  | otherwise = x:xs

module Main where

import Control.Monad
import Data.List

solve :: String -> Integer
solve = solve' []
 where
  solve' have ""
    | null have = 0
    | otherwise = 1
  solve' have (c : cs) =
    let have' = nub $ c : have
     in case length have' of
          4 -> 1 + solve' [] (c : cs)
          _ -> solve' have' cs

main :: IO ()
main = do
  t <- read <$> getLine
  replicateM_ t $
    getLine >>= print . solve

import Data.Set (Set, empty, insert, member, size)

calcH :: Set Char -> String -> Int
calcH _ [] = 1
calcH s (x: xs) = if (size s == 3) && (not (x `member` s))
  then calcH (insert x empty) xs + 1
  else calcH (insert x s) xs

calc :: String -> Int
calc a = calcH empty a

for :: Int -> IO ()
for 0 = pure ()
for i = do
  a <- getLine
  print $ calc a
  for $ i - 1

main :: IO ()
main = do
  n <- readLn :: IO Int
  for n

--
{-# LANGUAGE BlockArguments #-}
{-# LANGUAGE DatatypeContexts #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NumericUnderscores #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE Safe #-}
{-# LANGUAGE ScopedTypeVariables #-}
-- {-# LANGUAGE Strict #-}
{-# LANGUAGE TupleSections #-}
{-# OPTIONS_GHC -O3 -funbox-strict-fields -fvia-C -optc-O3 #-}

import Control.Arrow ((>>>))
import Control.Monad (
    MonadPlus (mplus),
    foldM_,
    forM_,
    guard,
    join,
    replicateM,
    replicateM_,
 )
import qualified Control.Monad as M
import qualified Control.Monad.ST.Strict as ST
import qualified Control.Monad.State.Strict as S
import qualified Control.Monad.Trans.Class as T

import qualified Data.Array as A
import qualified Data.Array.MArray.Safe as MA
import qualified Data.Array.IO.Safe as IOA
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.Int

import Data.Function (on)
import Data.Functor ((<&>))
import Data.Bifunctor (bimap)
import Data.Maybe (fromJust, fromMaybe, isJust)
import qualified Data.Maybe as MB

import qualified Data.IntMap as IM
import qualified Data.IntSet as IS
import qualified Data.List   as L
import Data.List (
    elemIndices,
    find,
    findIndices,
    intersect,
    isPrefixOf,
    nub,
    sort,
    sortOn,
 )
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.Ix as Ix
import qualified Data.Ratio as R

import Control.Monad.Cont (MonadIO (liftIO))
import Data.IORef (modifyIORef, newIORef, readIORef)
import GHC.IO.Handle (hDuplicateTo)
import System.IO (
    IOMode (ReadMode, WriteMode),
    openFile,
    stdin,
    stdout,
    hFlush
 )
import System.Posix.Internals (puts)
import Text.Printf (printf)
import qualified Data.Array.IO.Safe as UOA

-- import Debug.Trace (trace, traceM, traceShowM)
-- debug = flip trace
--
-- tracing t x = trace (t ++ " = " ++ show x) x
-- debugging x t = tracing t x

-- debug x t = x
-- trace t x = x
-- tracing t x = x
-- debugging x t = x

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

readIntB8s :: B8.ByteString -> [Int]
readIntB8s = B8.words >>> map (B8.readInt >>> (fst . fromJust))

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

readIntegerB8s :: B8.ByteString -> [Integer]
readIntegerB8s = B8.words >>> map (B8.readInteger >>> (fst . fromJust))

modifyArray :: (MA.MArray a e m, MA.Ix i) => a i e -> i -> (e -> e) -> m ()
modifyArray arr ix f = do
    value <- MA.readArray arr ix
    MA.writeArray arr ix $ f value

putsYesNo :: Bool -> IO ()
putsYesNo value = do
    let result :: String =
            if value
                then "YES"
                else "NO"
    printf "%s\n" result

{- END OF GENERAL -}

solve :: String -> Int
solve str = solve' str []
    where
        solve' :: String -> [Char] -> Int
        solve' [] _ = 1
        solve' s@(c:otherS) memory
            | L.length ([c] `L.union` memory) > 3 = 1 + solve' s []
            | otherwise = solve' otherS $ [c] `L.union` memory

main :: IO ()
main = do
    t <- B8.getLine <&> readIntB8
    replicateM_ t $ do
        s <- B8.getLine <&> head . B8.words
        let answer = solve (B8.unpack s)
        printf "%d\n" answer


Every year Santa Claus gives gifts to all children. However, each country has its own traditions, and this process takes place in different ways. For example, in Berland you need to solve the New Year's puzzle.Polycarp got the following problem: given a grid strip of size $$$2 \times n$$$, some cells of it are blocked. You need to check if it is possible to tile all free cells using the $$$2 \times 1$$$ and $$$1 \times 2$$$ tiles (dominoes).For example, if $$$n = 5$$$ and the strip looks like this (black cells are blocked):  Then it can be tiled, for example, using two vertical and two horizontal tiles, as in the picture below (different tiles are marked by different colors).  And if $$$n = 3$$$ and the strip looks like this:  It is impossible to tile free cells.Polycarp easily solved this task and received his New Year's gift. Can you solve it?

The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case is preceded by an empty line. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10^9$$$, $$$1 \le m \le 2 \cdot 10^5$$$) — the length of the strip and the number of blocked cells on it. Each of the next $$$m$$$ lines contains two integers $$$r_i, c_i$$$ ($$$1 \le r_i \le 2, 1 \le c_i \le n$$$) — numbers of rows and columns of blocked cells. It is guaranteed that all blocked cells are different, i.e. $$$(r_i, c_i) \ne (r_j, c_j), i \ne j$$$. It is guaranteed that the sum of $$$m$$$ over all test cases does not exceed $$$2 \cdot 10^5$$$.

For each test case, print on a separate line:    "YES", if it is possible to tile all unblocked squares with the $$$2 \times 1$$$ and $$$1 \times 2$$$ tiles;  "NO" otherwise.  You can output "YES" and "NO" in any case (for example, the strings yEs, yes, Yes and YES will be recognized as positive).

NoteThe first two test cases are explained in the statement.In the third test case the strip looks like this:    It is easy to check that the unblocked squares on it can not be tiled.

{-# LANGUAGE Safe #-}
{-# OPTIONS_GHC -O2 #-}

import safe Control.Arrow ((>>>))
import qualified Data.Text as T
import qualified Data.Text.IO as TI
import Data.List
import Data.Function
import Data.Maybe

main :: IO ()
main = TI.getContents >>= (T.lines >>> drop 1 >>> tcio >>> (mapM_ putStrLn)) where
  tcio :: [T.Text] -> [String]
  tcio [] = []
  tcio (_: nm : rest) = ((:[]). solve . linestoiss) (nm:(take m rest)) ++ tcio (drop m rest) where [n,m] = linetois nm;
  linetoi t = f 0 t where f n t = if (T.null) t then n else f (10*n + fromIntegral(on (-) fromEnum (T.head t) '0') ) (T.tail t) ;
  linetois = (map linetoi).(T.words); linestoiss = map linetois
  --itoline = show; istoline = unwords . (map itoline); isstolines = map istoline

solve :: [[Int]] -> String
solve ([n,m]:rcs) = if ans then "YES" else "NO" where
  (_,ans,_,_) = foldl' f (0, True, False, False) $ map (\cs->(head (head cs), map last cs)) $ groupBy ((==) `on` head) $ sort $ [n+1,1]:[n+1,2]: map reverse rcs
  f (bc, t0, t10, t01) (c,rs) = (c,v0,v10,v01) where
    (u0,u10,u01) = if odd (bc-c) then (t0,t10,t01) else (t0,t01,t10)
    v0 = (u0 && rs == [1,2]) || (u10 && rs == [2]) || (u01 && rs == [1])
    v10 = (u0 && rs == [2])
    v01 = (u0 && rs == [1])


A batch of $$$n$$$ goods ($$$n$$$ — an even number) is brought to the store, $$$i$$$-th of which has weight $$$a_i$$$. Before selling the goods, they must be packed into packages. After packing, the following will be done:   There will be $$$\frac{n}{2}$$$ packages, each package contains exactly two goods;  The weight of the package that contains goods with indices $$$i$$$ and $$$j$$$ ($$$1 \le i, j \le n$$$) is $$$a_i + a_j$$$. With this, the cost of a package of weight $$$x$$$ is always $$$\left \lfloor\frac{x}{k}\right\rfloor$$$ burles (rounded down), where $$$k$$$ — a fixed and given value.Pack the goods to the packages so that the revenue from their sale is maximized. In other words, make such $$$\frac{n}{2}$$$ pairs of given goods that the sum of the values $$$\left \lfloor\frac{x_i}{k} \right \rfloor$$$, where $$$x_i$$$ is the weight of the package number $$$i$$$ ($$$1 \le i \le \frac{n}{2}$$$), is maximal.For example, let $$$n = 6, k = 3$$$, weights of goods $$$a = [3, 2, 7, 1, 4, 8]$$$. Let's pack them into the following packages.   In the first package we will put the third and sixth goods. Its weight will be $$$a_3 + a_6 = 7 + 8 = 15$$$. The cost of the package will be $$$\left \lfloor\frac{15}{3}\right\rfloor = 5$$$ burles.  In the second package put the first and fifth goods, the weight is $$$a_1 + a_5 = 3 + 4 = 7$$$. The cost of the package is $$$\left \lfloor\frac{7}{3}\right\rfloor = 2$$$ burles.  In the third package put the second and fourth goods, the weight is $$$a_2 + a_4 = 2 + 1 = 3$$$. The cost of the package is $$$\left \lfloor\frac{3}{3}\right\rfloor = 1$$$ burle. With this packing, the total cost of all packs would be $$$5 + 2 + 1 = 8$$$ burles.

The first line of the input contains an integer $$$t$$$ ($$$1 \le t \le 10^4$$$) —the number of test cases in the test. The descriptions of the test cases follow. The first line of each test case contains two integers $$$n$$$ ($$$2 \le n \le 2\cdot10^5$$$) and $$$k$$$ ($$$1 \le k \le 1000$$$). The number $$$n$$$ — is even. The second line of each test case contains exactly $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all the test cases does not exceed $$$2\cdot10^5$$$.

For each test case, print on a separate line a single number — the maximum possible total cost of all the packages.

NoteThe first test case is analyzed in the statement.In the second test case, you can get a total value equal to $$$4$$$ if you put the first and second goods in the first package and the third and fourth goods in the second package.In the third test case, the cost of each item is $$$0$$$, so the total cost will also be $$$0$$$.

{-# OPTIONS_GHC -O2 #-}

import Data.List
import Data.Maybe
import qualified Data.Map.Strict as Map

main = do
  tStr <- getLine
  let t = read tStr :: Int
  input <- getContents
  let sols = map (format . solve . parse) $ take t $ sep $ lines input
  mapM_ putStrLn sols

sep (x:y:xs) = (x,y):(sep xs)

parse (x,y) = (read $ (words x) !! 1, map read $ words y)

format = show

solve (k,as) = base + extra
  where base = sum ds
        (ds, ms) = unzip $ map (`divMod` k) as
        msAsc = sort ms
        msDes = reverse msAsc
        l = length ms
        extra = cnt 0 0 (l-1) msDes msAsc
        cnt s i j _ _
          | i >= j = s
        cnt s i j (x:xs) (y:ys)
          | x + y >= k = cnt (s+1) (i+1) (j-1) xs ys
          | otherwise = cnt s i (j-1) (x:xs) ys

{-# OPTIONS_GHC -O2 #-}

import Data.List
import Data.Maybe
import qualified Data.Map.Strict as Map

main = do
  tStr <- getLine
  let t = read tStr :: Int
  input <- getContents
  let sols = map (format . solve . parse) $ take t $ sep $ lines input
  mapM_ putStrLn sols

sep (x:y:xs) = (x,y):(sep xs)

parse (x,y) = (read $ (words x) !! 1, map read $ words y)

format = show

solve (k,as) = base + extra
  where base = sum ds
        (ds, ms) = unzip $ map (`divMod` k) as
        msAsc = sort ms
        msDes = reverse msAsc
        l = length ms
        extra = cnt 0 (l-1) msDes msAsc
        cnt i j _ _
          | i >= j = 0
        cnt i j (x:xs) (y:ys)
          | x + y >= k = 1 + cnt (i+1) (j-1) xs ys
          | otherwise = cnt i (j-1) (x:xs) ys

module Main where

import Data.List
import Data.Maybe
import qualified Data.Map.Strict as Map

main = do
  tStr <- getLine
  let t = read tStr :: Int
  input <- getContents
  let sols = map (format . solve . parse) $ take t $ sep $ lines input
  mapM_ putStrLn sols

sep (x:y:xs) = (x,y):(sep xs)

parse (x,y) = (read $ (words x) !! 1, map read $ words y)

format = show

solve (k,as) = base + extra
  where base = sum ds
        (ds, ms) = unzip $ map (`divMod` k) as
        msAsc = sort ms
        msDes = reverse msAsc
        l = length ms
        extra = cnt 0 (l-1) msDes msAsc
        cnt i j _ _
          | i >= j = 0
        cnt i j (x:xs) (y:ys)
          | x + y >= k = 1 + cnt (i+1) (j-1) xs ys
          | otherwise = cnt i (j-1) (x:xs) ys


Being tired of participating in too many Codeforces rounds, Gildong decided to take some rest in a park. He sat down on a bench, and soon he found two rabbits hopping around. One of the rabbits was taller than the other.He noticed that the two rabbits were hopping towards each other. The positions of the two rabbits can be represented as integer coordinates on a horizontal line. The taller rabbit is currently on position $$$x$$$, and the shorter rabbit is currently on position $$$y$$$ ($$$x \lt y$$$). Every second, each rabbit hops to another position. The taller rabbit hops to the positive direction by $$$a$$$, and the shorter rabbit hops to the negative direction by $$$b$$$.  For example, let's say $$$x=0$$$, $$$y=10$$$, $$$a=2$$$, and $$$b=3$$$. At the $$$1$$$-st second, each rabbit will be at position $$$2$$$ and $$$7$$$. At the $$$2$$$-nd second, both rabbits will be at position $$$4$$$.Gildong is now wondering: Will the two rabbits be at the same position at the same moment? If so, how long will it take? Let's find a moment in time (in seconds) after which the rabbits will be at the same point.

Each test contains one or more test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 1000$$$). Each test case contains exactly one line. The line consists of four integers $$$x$$$, $$$y$$$, $$$a$$$, $$$b$$$ ($$$0 \le x \lt y \le 10^9$$$, $$$1 \le a,b \le 10^9$$$) — the current position of the taller rabbit, the current position of the shorter rabbit, the hopping distance of the taller rabbit, and the hopping distance of the shorter rabbit, respectively.

For each test case, print the single integer: number of seconds the two rabbits will take to be at the same position. If the two rabbits will never be at the same position simultaneously, print $$$-1$$$.

NoteThe first case is explained in the description.In the second case, each rabbit will be at position $$$3$$$ and $$$7$$$ respectively at the $$$1$$$-st second. But in the $$$2$$$-nd second they will be at $$$6$$$ and $$$4$$$ respectively, and we can see that they will never be at the same position since the distance between the two rabbits will only increase afterward.

module Main where

main :: IO ()
main = interact $ unlines . map (show . solve . readIntegers) . takeNLines . lines
  where
  takeNLines (l:ls) = take (read l) ls
  readIntegers = map read . words

solve :: [Integer] -> Integer
solve ls =
  case mod diff summ of
    0 -> div diff summ
    _ -> -1
  where
  diff = (ls !! 1 - ls !! 0)
  summ = (ls !! 2 + ls !! 3)

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

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

type EIO a = ExceptT String IO a

data HNormal
data HString
data HList

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

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

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

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

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

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

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

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

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

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

f1 :: EIO ()
f1 = do
    (x, y, a, b) <- liftM4 (,,,) get get get get
    putln $ f2 x y a b

f2 :: Int64 -> Int64 -> Int64 -> Int64 -> Int64
f2 x y a b =    let d = (div (y - x) (a + b)) in
                let r = (mod (y - x) (a + b)) in
                if r /= 0 || d < 0 then -1
                else d

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

process [a,b,c,d] | mod  (b-a) (c+d)>0 = -1
                  | otherwise = div (b-a) (c+d)

main::IO ()
main=do
  t<- read<$> getLine ::IO Int
  a<-  map(map read. words) <$> replicateM t getLine::IO [[Integer]]
  mapM_ print $ map process a

process :: (Int, Int, Int, Int) -> Int
process (x,y,a,b)
    | r == 0 = q
    | otherwise = -1
    where
        d = y-x
        c = a+b
        r = d `mod` c
        q = d `div` c

readInt :: String -> Int
readInt = read

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

parse :: String -> String
parse input = show $ solve x y a b
  where [x, y, a, b] = map (\x -> read x :: Integer) $ words input

solve :: Integer -> Integer -> Integer -> Integer -> Integer
solve x y a b
  | mod (y-x) (a+b) == 0 = div (y-x) (a+b)
  | otherwise = -1

main :: IO ()
main = interact (unlines . map parse . tail . lines)


Polycarp started working at a bank. He was assigned to monitor the ATM. The ATM initially contains $$$s$$$ rubles.A queue of $$$n$$$ students lined up to him. Each student wants to either withdraw a certain amount of money or deposit it into an account. If $$$a_i$$$ is positive, then the student credits that amount of money via ATM. Otherwise, the student withdraws $$$|a_i|$$$ rubles.In the beginning, the ATM is turned off and an arbitrary number of students are not served. At some point, Polycarp turns on the ATM, which has an initial amount of $$$s$$$ rubles. Then, the remaining students start queueing at the ATM. If at some point in time there is less money in the ATM than the student wants to withdraw, then the student is not served and Polycarp turns off the ATM and does not turn it on anymore.More formally, the students that are served are forming a contiguous subsequence.Polycarp wants the ATM to serve the maximum number of students. Help him in this matter. Print the numbers of the first and last student, or determine that he will not be able to serve anyone.In other words, find such a longest continuous segment of students that, starting with the sum of $$$s$$$ at the ATM, all these students will be served. ATM serves students consistently (i.e. one after another in the order of the queue).

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Each test case consists of two lines. The first one contains integers $$$n$$$ and $$$s$$$ ($$$1 \le n \le 2\cdot10^5$$$; $$$0 \le s \le 10^9$$$) — the length of the $$$a$$$ array and the initial amount of rubles in the ATM. The second contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$) — elements of the $$$a$$$ array. Note that $$$a_i$$$ can be zero. It is guaranteed that the sum of the values $$$n$$$ over all test cases does not exceed $$$2\cdot10^5$$$.

Print $$$t$$$ lines, each line must contain the answer to the corresponding set of input data: if the answer exists, print the numbers of the first and last served student. If there is no solution, then print -1 on the line. If there are several possible answers, print any.

NoteIn the first test case, the only correct answer is 2 4, since when serving students, the number of rubles at the ATM does not become negative, and this is the maximum number of students that can be served.In the second test case, the answer is -1, as there is not enough money for any student at the ATM.In the third test case, the answer can be either 1 2 or 4 5.

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

import qualified Data.ByteString.Lazy.Char8 as P
import qualified Data.ByteString.Char8 as String
import qualified Data.ByteString.Builder.Prim as Prim
import Data.ByteString.Builder
import Control.Monad
import Control.Monad.ST
--import Control.Monad.Trans.State
import Data.Array.Base
import Data.Array.IO
import Data.Array.ST
import Data.Array.Unboxed
import Data.Array.MArray as Vector
import Data.Bits
import Data.Bool
import Data.Char
import Data.Graph
import Data.Int
import Data.List
import Data.Maybe
import Data.Ord
import Data.Ratio
import Data.Tuple
import Data.Function
import qualified Data.Set as Set
import qualified Data.Sequence as Seq
import System.IO
import System.IO.Unsafe
import System.Exit

import Data.IORef
import Control.Monad.Writer
import Control.Monad.State
import Control.Monad.Fail
import Control.Applicative
import Control.Monad.Except
import Control.Monad.Reader
import Control.Monad.Trans.Except
import Control.Monad.IO.Class (liftIO)
import Data.Foldable (msum)
import Data.Char (isNumber, isPunctuation)

import Control.Monad.Identity (Identity(..))

printLog :: Show a => a -> a
printLog a = unsafePerformIO $ do putStrLn $ "{отладка[ "++show a ++ " ]отладка}"
                                  pure a

fArray :: Ix i => (i, i) -> (i -> a) -> Array i a
fArray b f = array b [(i, f i) | i <- range b]

printArray = putStrLn . unwords . map show . elems

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

data SegTree a b = Empty |
               SegTree { subtL :: SegTree a b
                       , segL :: a
                       , segR :: a
                       , valOnSeg :: b
                       , subtR :: SegTree a b
                       } deriving Show

intINF = maxBound::Int

getVal :: SegTree a Int -> Int
getVal Empty = intINF
getVal tree = valOnSeg tree

buildSegTree :: Int -> Int -> UArray Int Int -> SegTree Int Int
buildSegTree l r arr
  | l+1==r = SegTree Empty l r (arr!l) Empty
  | otherwise = SegTree left l r (min (getVal left) (getVal right)) right
    where mid = (l + r) `div` 2
          left = buildSegTree l mid arr
          right = buildSegTree mid r arr

getMin :: Int -> Int -> SegTree Int Int -> Int
getMin l r Empty = intINF
getMin l r (SegTree subtl tl tr mn subtr)
  | tl >= r || tr <= l = intINF
  | l <= tl && tr <= r = mn
  | otherwise = min (getMin l r subtl) (getMin l r subtr)
    where mid = (tl+tr) `div` 2

binSearch :: Show b => Integral i => (i -> (Bool, Maybe b)) -> i -> i -> (i, Maybe b)
binSearch f = go where
    go l r
        | l > r     = (l, Nothing)
        | not good = go l (mid - 1)
        | otherwise = let ful@(ans, val') = go (mid + 1) r in
                        if (isNothing val') then (mid, val) else ful
        where mid = (l + r) `div` 2
              (good, val) = f mid

fita :: IO ()
fita = do
  [n,s] <- readInts
  arr <- readInts
  let psum = (listArray (0,n-1) $ drop 1 . reverse $ foldl (\pref el -> (el+head pref):pref) [0] arr) :: UArray Int Int
      segtree = buildSegTree 0 n psum

      getP 0 = 0
      getP n = psum ! (n-1)
      checker len = maybe (False, Nothing) id
                    . find fst
                    . map (\(l,r) -> ((getMin l (r+1) segtree - getP l >= (-s)), Just (l,r))) $ zip [0,1..] [len-1..n-1]
      (_, ans) = (binSearch checker 1 n) :: (Int, Maybe (Int, Int))
      parseAns Nothing = "-1"
      parseAns (Just (l, r)) = show (l+1) ++" "++ show (r+1)
  --printArray psum
  --print segtree
  putStrLn $ parseAns ans

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


NIT, the cleaver, is new in town! Thousands of people line up to orz him. To keep his orzers entertained, NIT decided to let them solve the following problem related to $$$\operatorname{or} z$$$. Can you solve this problem too?You are given a 1-indexed array of $$$n$$$ integers, $$$a$$$, and an integer $$$z$$$. You can do the following operation any number (possibly zero) of times:  Select a positive integer $$$i$$$ such that $$$1\le i\le n$$$. Then, simutaneously set $$$a_i$$$ to $$$(a_i\operatorname{or} z)$$$ and set $$$z$$$ to $$$(a_i\operatorname{and} z)$$$. In other words, let $$$x$$$ and $$$y$$$ respectively be the current values of $$$a_i$$$ and $$$z$$$. Then set $$$a_i$$$ to $$$(x\operatorname{or}y)$$$ and set $$$z$$$ to $$$(x\operatorname{and}y)$$$. Here $$$\operatorname{or}$$$ and $$$\operatorname{and}$$$ denote the bitwise operations OR and AND respectively.Find the maximum possible value of the maximum value in $$$a$$$ after any number (possibly zero) of operations.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$z$$$ ($$$1\le n\le 2000$$$, $$$0\le z<2^{30}$$$). The second line of each test case contains $$$n$$$ integers $$$a_1$$$,$$$a_2$$$,$$$\ldots$$$,$$$a_n$$$ ($$$0\le a_i<2^{30}$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^4$$$.

For each test case, print one integer — the answer to the problem.

NoteIn the first test case of the sample, one optimal sequence of operations is:  Do the operation with $$$i=1$$$. Now $$$a_1$$$ becomes $$$(3\operatorname{or}3)=3$$$ and $$$z$$$ becomes $$$(3\operatorname{and}3)=3$$$.  Do the operation with $$$i=2$$$. Now $$$a_2$$$ becomes $$$(4\operatorname{or}3)=7$$$ and $$$z$$$ becomes $$$(4\operatorname{and}3)=0$$$.  Do the operation with $$$i=1$$$. Now $$$a_1$$$ becomes $$$(3\operatorname{or}0)=3$$$ and $$$z$$$ becomes $$$(3\operatorname{and}0)=0$$$. After these operations, the sequence $$$a$$$ becomes $$$[3,7]$$$, and the maximum value in it is $$$7$$$. We can prove that the maximum value in $$$a$$$ can never exceed $$$7$$$, so the answer is $$$7$$$.In the fourth test case of the sample, one optimal sequence of operations is:  Do the operation with $$$i=1$$$. Now $$$a_1$$$ becomes $$$(7\operatorname{or}7)=7$$$ and $$$z$$$ becomes $$$(7\operatorname{and}7)=7$$$.  Do the operation with $$$i=3$$$. Now $$$a_3$$$ becomes $$$(30\operatorname{or}7)=31$$$ and $$$z$$$ becomes $$$(30\operatorname{and}7)=6$$$.  Do the operation with $$$i=5$$$. Now $$$a_5$$$ becomes $$$(27\operatorname{or}6)=31$$$ and $$$z$$$ becomes $$$(27\operatorname{and}6)=2$$$.

--
-- Michael V. Antosha
-- 2022
-- Michael.Antosha@gmail.com
--

{-# language Safe                      #-}
{-# language ImportQualifiedPost       #-}
{-# language NoMonomorphismRestriction #-}

{-# options_ghc -O3                              #-}

{-# options_ghc -Weverything                     #-}
{-# options_ghc -Werror                          #-}

{-# options_ghc -Wno-missing-import-lists        #-}
{-# options_ghc -Wno-missing-local-signatures    #-}

import Prelude               hiding (getLine)
import Control.Arrow
import Control.Monad
import Data.ByteString.Char8 qualified as B
import Data.Char
import Data.List             qualified as L
import Data.Bits

ri = readInts <$> B.getLine :: IO [Int]
  where
    readInts  = L.unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace
    dropSpace = B.dropWhile isSpace

main :: IO ()
main = do
    [t] <- ri
    tcs <- replicateM t $ do
        [_n,z] <- ri
        xs     <- ri
        return (z,xs)
    mapM_ (putStrLn . show . solve) tcs

solve (z,xs) = maximum . map (.|. z) $ xs


A remote island chain contains n islands, labeled 1 through n. Bidirectional bridges connect the islands to form a simple cycle — a bridge connects islands 1 and 2, islands 2 and 3, and so on, and additionally a bridge connects islands n and 1. The center of each island contains an identical pedestal, and all but one of the islands has a fragile, uniquely colored statue currently held on the pedestal. The remaining island holds only an empty pedestal.The islanders want to rearrange the statues in a new order. To do this, they repeat the following process: First, they choose an island directly adjacent to the island containing an empty pedestal. Then, they painstakingly carry the statue on this island across the adjoining bridge and place it on the empty pedestal.Determine if it is possible for the islanders to arrange the statues in the desired order.

The first line contains a single integer n (2 ≤ n ≤ 200 000) — the total number of islands. The second line contains n space-separated integers ai (0 ≤ ai ≤ n - 1) — the statue currently placed on the i-th island. If ai = 0, then the island has no statue. It is guaranteed that the ai are distinct. The third line contains n space-separated integers bi (0 ≤ bi ≤ n - 1) — the desired statues of the ith island. Once again, bi = 0 indicates the island desires no statue. It is guaranteed that the bi are distinct.

Print "YES" (without quotes) if the rearrangement can be done in the existing network, and "NO" otherwise.

NoteIn the first sample, the islanders can first move statue 1 from island 1 to island 2, then move statue 2 from island 3 to island 1, and finally move statue 1 from island 2 to island 3.In the second sample, the islanders can simply move statue 1 from island 1 to island 2.In the third sample, no sequence of movements results in the desired position.

{-
instructions go here...
-}

module Main where
import Data.List (findIndex)

solve :: [Int] -> [Int] -> Bool
solve initial target = normalize initial == normalize target

normalize lst = filter (/= 0) $ after ++ before
  where (Just zeroPos) = findIndex (== 1) lst
        (before, after) = splitAt zeroPos lst

main :: IO ()
main = do
  line1 <- getLine
  let n = read line1 :: Int
  line2 <- getLine
  let initial = map read (words line2) :: [Int]
  line3 <- getLine
  let target = map read (words line3) :: [Int]
  putStrLn $ if solve initial target
               then "YES"
               else "NO"


Kolya got an integer array $$$a_1, a_2, \dots, a_n$$$. The array can contain both positive and negative integers, but Kolya doesn't like $$$0$$$, so the array doesn't contain any zeros.Kolya doesn't like that the sum of some subsegments of his array can be $$$0$$$. The subsegment is some consecutive segment of elements of the array. You have to help Kolya and change his array in such a way that it doesn't contain any subsegments with the sum $$$0$$$. To reach this goal, you can insert any integers between any pair of adjacent elements of the array (integers can be really any: positive, negative, $$$0$$$, any by absolute value, even such a huge that they can't be represented in most standard programming languages).Your task is to find the minimum number of integers you have to insert into Kolya's array in such a way that the resulting array doesn't contain any subsegments with the sum $$$0$$$.

The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 200\,000$$$) — the number of elements in Kolya's array. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^{9} \le a_i \le 10^{9}, a_i \neq 0$$$) — the description of Kolya's array.

Print the minimum number of integers you have to insert into Kolya's array in such a way that the resulting array doesn't contain any subsegments with the sum $$$0$$$.

NoteConsider the first example. There is only one subsegment with the sum $$$0$$$. It starts in the second element and ends in the fourth element. It's enough to insert one element so the array doesn't contain any subsegments with the sum equal to zero. For example, it is possible to insert the integer $$$1$$$ between second and third elements of the array.There are no subsegments having sum $$$0$$$ in the second example so you don't need to do anything.

import Control.Arrow ((>>>))
import qualified Data.Set as Set

main :: IO ()
main =
  interact $
    lines
      >>> drop 1
      >>> head
      >>> words
      >>> map read
      >>> solve
      >>> show
      >>> (++ "\n")

type SetInt = Set.Set Integer

solve :: [Integer] -> Integer
solve a = compute (Set.singleton 0) 0 a

compute :: SetInt -> Integer -> [Integer] -> Integer
compute _ _ [] = 0
compute pres pre (x : a) =
  if Set.member pre' pres
    then 1 + compute (Set.fromList [x, 0]) x a
    else compute (Set.insert pre' pres) pre' a
  where pre' = pre + x

import Control.Monad
import Data.Set (Set, insert, member, empty)

getList :: (Read t) => IO [t]
getList = getLine >>= return . (map read) . words

getOne :: (Read t) => IO t
getOne = getLine >>= return . read

main :: IO ()
main = do
  -- t <- getOne
  let t = 1
  replicateM_ t solve

solve :: IO ()
solve = do
  n <- getOne :: IO Int
  ls <- getList
  print $ countAns ls

includeZero :: Integral a => Set a
includeZero = 0 `insert` empty

countAns :: (Integral a) => [a] -> a
countAns ls = countZeros includeZero ls 0

countZeros :: (Integral a) => Set a -> [a] -> a -> a
countZeros _ [] _ = 0
countZeros sums all@(x:xs) sum
  | ns `member` sums = 1 + countZeros includeZero all 0
  | otherwise = countZeros (ns `insert` sums) xs ns
  where ns = sum + x

import Data.List ( foldl' )
import Data.Int
import qualified Data.Set as Set

data State = State !Int64 !(Set.Set Int64) !Int

step :: State -> Int64 -> State
step (State currPS activePS count) v = let
  nextPS = v + currPS
  in  if  Set.member nextPS activePS
  then  State v (Set.fromList [0, v]) (count + 1)
  else  State nextPS (Set.insert nextPS activePS) count

solve :: [Int64] -> Int
solve li = let
  State _ _ ct = foldl' step (State 0 (Set.singleton 0) 0) li
  in  ct

main :: IO ()
main = do
  _nStr <- getLine
  a <- map read . words <$> getLine
  print $ solve a

import qualified Data.Set as S

main :: IO ()
main = do
    _ <- getLine
    a <- map read . words <$> getLine
    print $ (\(_, y, _) -> y) $ foldl processElem (S.singleton 0, 0, 0) $ scanl1 (+) a

processElem :: (S.Set Integer, Integer, Integer) -> Integer -> (S.Set Integer, Integer, Integer)
processElem (s, c, p) x
                   | S.member x s = (S.fromList [p, x], c + 1, x)
                   | otherwise = (S.insert x s, c, x)

import Data.Set
import Data.Int

countDup :: Set Int64 -> Int64 -> [Int64] -> Int
countDup _ _ [] = 0
countDup seen last (head:tail)
  | member head seen = 1 + countDup (fromList [last, head]) head tail
  | otherwise = countDup (insert head seen) head tail

solve :: [Int64] -> Int
solve a = countDup (singleton 0) 0 cum
  where cum = scanl1 (+) a

main = do
  _ <- getLine
  sa <- getLine
  let a = [read x :: Int64 | x <- words sa]
  putStrLn $ show $ solve a

import Data.Set

countDup :: Set Int -> Int -> [Int] -> Int
countDup _ _ [] = 0
countDup seen last (head:tail)
  | member head seen = 1 + countDup (fromList [last, head]) head tail
  | otherwise = countDup (insert head seen) head tail

solve :: [Int] -> Int
solve a = countDup (singleton 0) 0 cum
  where cum = scanl1 (+) a

main = do
  _ <- getLine
  sa <- getLine
  let a = [read x :: Int | x <- words sa]
  putStrLn $ show $ solve a


You are given two strings $$$s$$$ and $$$t$$$, both consisting only of lowercase Latin letters.The substring $$$s[l..r]$$$ is the string which is obtained by taking characters $$$s_l, s_{l + 1}, \dots, s_r$$$ without changing the order.Each of the occurrences of string $$$a$$$ in a string $$$b$$$ is a position $$$i$$$ ($$$1 \le i \le |b| - |a| + 1$$$) such that $$$b[i..i + |a| - 1] = a$$$ ($$$|a|$$$ is the length of string $$$a$$$).You are asked $$$q$$$ queries: for the $$$i$$$-th query you are required to calculate the number of occurrences of string $$$t$$$ in a substring $$$s[l_i..r_i]$$$.

The first line contains three integer numbers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 10^3$$$, $$$1 \le q \le 10^5$$$) — the length of string $$$s$$$, the length of string $$$t$$$ and the number of queries, respectively. The second line is a string $$$s$$$ ($$$|s| = n$$$), consisting only of lowercase Latin letters. The third line is a string $$$t$$$ ($$$|t| = m$$$), consisting only of lowercase Latin letters. Each of the next $$$q$$$ lines contains two integer numbers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$) — the arguments for the $$$i$$$-th query.

Print $$$q$$$ lines — the $$$i$$$-th line should contain the answer to the $$$i$$$-th query, that is the number of occurrences of string $$$t$$$ in a substring $$$s[l_i..r_i]$$$.

NoteIn the first example the queries are substrings: "cod", "deforces", "fo" and "for", respectively.

{-# LANGUAGE ViewPatterns #-}
module Main where
import Data.List
import Data.Array.Unboxed

default (Int)

main = interact exec
exec = unlines . map show . (\(_:_:_:xs:ys:(map read -> qs)) -> go (build xs ys) (length ys) qs) . words
go _ _ [] = []
go t ny (l:r:qs) = max 0 (t!max 0 (r - ny + 1) - t!(l - 1)):go t ny qs
build xs ys | nx <- length xs = listArray (0, nx) $ scanl (+) 0 $ map (fromEnum . (ys `isPrefixOf`)) $ tails xs :: UArray Int Int


You are given array a with n integers and m queries. The i-th query is given with three integers li, ri, xi.For the i-th query find any position pi (li ≤ pi ≤ ri) so that api ≠ xi.

The first line contains two integers n, m (1 ≤ n, m ≤ 2·105) — the number of elements in a and the number of queries. The second line contains n integers ai (1 ≤ ai ≤ 106) — the elements of the array a. Each of the next m lines contains three integers li, ri, xi (1 ≤ li ≤ ri ≤ n, 1 ≤ xi ≤ 106) — the parameters of the i-th query.

Print m lines. On the i-th line print integer pi — the position of any number not equal to xi in segment [li, ri] or the value  - 1 if there is no such number.

{-# OPTIONS_GHC -O2 #-}

import Control.Applicative ((<$>))
import Data.Array (Array)
import Data.Array.IArray (accumArray, array, listArray, bounds, amap, (!))
import Control.Monad (replicateM)
import Data.ByteString.Char8 (words, lines, readInt, getLine, getContents)
import Data.Maybe (fromJust)
import Prelude hiding (words, lines, getLine, getContents)

readInt' = fst . fromJust . readInt
readInts = map readInt' . words <$> getLine

main = do
  [n, m] <- readInts
  as <- readInts

  qs <- replicateM m readInts :: IO [[Int]]

  let
    ps1 = accumArray (flip (:)) [] (1, 10^6) $ zip as [1..n] :: Array Int [Int]
    ps = amap (compact . reverse) ps1
      where
        compact :: [Int] -> Array Int (Int, Int)
        compact [] = array (1,0) []
        compact (i:is) = listArray (1, length l) l :: Array Int (Int, Int)
          where
            l = f i i is
              where
                f i j [] = [(i,j)]
                f i j (k:is)
                  | k == j+1 = f i k is
                  | otherwise = (i,j):(f k k is)

    ys = map solve qs
      where
        solve [l, r, x]
          | b2 == 0 = l
          | otherwise = f $ lookup 1 b2
          where
            b2 = snd $ bounds rs
            rs = ps ! x

            lookup i j
              | i >= j = if l <= rr && ll <= r then Just m else Nothing
              | l > rr = lookup (m + 1) j
              | ll > r = lookup i m
              | otherwise = Just m
              where
                m = (i+j) `div` 2
                (ll, rr) = rs ! m

            f Nothing = l
            f (Just m)
              | ll <= l && r <= rr = -1
              | r > rr = rr + 1
              | l < ll = ll-1
              where
                (ll, rr) = rs ! m

  putStr $ unlines $ map show ys

import Control.Monad
import Data.Array.Unboxed
import Data.Maybe
import Data.List
import qualified Data.ByteString.Char8 as B
type Vi = UArray Int Int
type Pii = (Int, Int, Int, Int)

readB s = a
    where Just (a,_) = B.readInt s

main = do
    input <- liftM (map readB . B.words) (B.getLine >> B.getLine) :: IO [Int]
    let tuple = unzip4 $ (map snd) $ scanl build (0, (-1,-1, -1,-1)) input
    let [a,ai,b,bi] = ((map (listArray (0, length input))).(\(a,b,c,d)->[a,b,c,d])$tuple) :: [Vi]
    B.getContents >>= putStr . unlines . (map (show.solve a ai b bi.map readB. B.words)).  B.lines

build :: (Int, Pii) -> Int -> (Int, Pii)
build (i, (a,ai,b,bi)) n
    | n==a      = ((i+1), (a,(i+1),b,bi))
    | otherwise = ((i+1), (n,(i+1),a,ai))

solve :: Vi->Vi->Vi->Vi -> [Int] -> Int
solve x xi y yi [l,r,val]
    | (x!r)==val = if ((yi!r)>=l) then (yi!r) else (-1)
    | otherwise = (xi!r)

import Control.Monad
import qualified Data.Map.Strict as Map
import Data.Maybe
import qualified Data.ByteString.Char8 as B

readB s = a
    where Just (a,_) = B.readInt s

main = do
    a <- liftM (map readB . B.words) (B.getLine >> B.getLine) :: IO [Int]
    let b = Map.fromList $ scanl build (0, ((-1,-1), (-1,-1))) a
    B.getContents >>= putStr . unlines . (map (show.(solve b).(map readB). B.words)). B.lines

build (i, ((a,ai), (b,bi))) n
    | n==a      = ((i+1), ((a,(i+1)), (b,bi)))
    | otherwise = ((i+1), ((n,(i+1)), (a,ai)))

solve :: Map.Map Int ((Int,Int),(Int,Int)) -> [Int] -> Int
solve b [l,r,val]
    | x==val = if (yi>=l) then yi else (-1)
    | otherwise = xi
    where
        ((x,xi),(y,yi)) = fromJust $ Map.lookup r b

import Control.Monad
import Data.Array
import Data.Maybe
import qualified Data.ByteString.Char8 as B

readB s = a
    where Just (a,_) = B.readInt s

main = do
    a <- liftM (map readB . B.words) (B.getLine >> B.getLine) :: IO [Int]
    let b = listArray (0, length a) $ (map snd) $ scanl build (0, ((-1,-1), (-1,-1))) a
    B.getContents >>= putStr . unlines . (map (show.(solve b).(map readB). B.words)).  B.lines

build (i, ((a,ai), (b,bi))) n
    | n==a      = ((i+1), ((a,(i+1)), (b,bi)))
    | otherwise = ((i+1), ((n,(i+1)), (a,ai)))

solve b [l,r,val]
    | x==val = if (yi>=l) then yi else (-1)
    | otherwise = xi
    where
        ((x,xi),(y,yi)) = b!r

import Data.Array
import qualified Data.ByteString.Char8 as B
import Data.Maybe
import Control.Monad
import Control.Applicative

main = do
    let b2i = fst . fromJust . B.readInt
    [n, m] <- map b2i . B.words <$> B.getLine
    a <- map b2i . B.words <$> B.getLine
    mls <- forM [1..m] $ const B.getLine
    let lrx = map ((\[l, r, x] -> (l, r, x)) . map b2i . B.words) (mls::[B.ByteString])
    mapM_ (putStrLn . show) $ sol n m a lrx

sol :: Int -> Int -> [Int] -> [(Int, Int, Int)] -> [Int]
sol n m alst lrx = map query lrx
    where
    a = listArray (1, n) alst
    lastDif = listArray (1, n) [dp loc | loc <- [1..n]]
    dp l
      | l == 1 = -1
      | a ! l == a ! (l-1) = lastDif ! (l-1)
      | otherwise = l-1
    query (l, r, x)
        | a ! r /= x = r
        | lastDif ! r >= l = lastDif ! r
        | otherwise = -1

import Control.Monad
import Data.Array.Unboxed
import Data.Maybe
import Data.List
import qualified Data.ByteString.Char8 as B
type Vi = UArray Int Int
type Pii = (Int, Int, Int, Int)

readB s = a
    where Just (a,_) = B.readInt s

main = do
    input <- liftM (map read . words) (getLine >> getLine) :: IO [Int]
    let tuple = unzip4 $ (map snd) $ scanl build (0, (-1,-1, -1,-1)) input
    let [a,ai,b,bi] = ((map (listArray (0, length input))).(\(a,b,c,d)->[a,b,c,d])$tuple) :: [Vi]
    B.getContents >>= putStr . unlines . (map (show.solve a ai b bi.map readB. B.words)).  B.lines

build :: (Int, Pii) -> Int -> (Int, Pii)
build (i, (a,ai,b,bi)) n
    | n==a      = ((i+1), (a,(i+1),b,bi))
    | otherwise = ((i+1), (n,(i+1),a,ai))

solve :: Vi->Vi->Vi->Vi -> [Int] -> Int
solve x xi y yi [l,r,val]
    | (x!r)==val = if ((yi!r)>=l) then (y!r) else (-1)
    | otherwise = (xi!r)

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

main = do
    a <- liftM (map read . words) (getLine >> getLine) :: IO [Int]
    let b = Map.fromList $ scanl build (1, ((-1,-1), (-1,-1))) a
    getContents >>= putStr . unlines . (map (show.(solve b).(map read).words)).lines

build (i, ((a,ai), (b,bi))) n
    | n==a      = ((i+1), ((a,i), (b,bi)))
    | otherwise = ((i+1), ((n,i), (a,ai)))

solve :: Map.Map Int ((Int,Int),(Int,Int)) -> [Int] -> Int
solve b [l,r,val]
    | x==val = if (yi>=l) then yi else (-1)
    | otherwise = xi
    where
        ((x,xi),(y,yi)) = fromJust $ Map.lookup r b


You are given three integers $$$n$$$, $$$l$$$, and $$$r$$$. You need to construct an array $$$a_1,a_2,\dots,a_n$$$ ($$$l\le a_i\le r$$$) such that $$$\gcd(i,a_i)$$$ are all distinct or report there's no solution.Here $$$\gcd(x, y)$$$ denotes the greatest common divisor (GCD) of integers $$$x$$$ and $$$y$$$.

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1\le t\le 10^4$$$) — the number of test cases. The description of the test cases follows. The first line contains three integers $$$n$$$, $$$l$$$, $$$r$$$ ($$$1 \le n \le 10^5$$$, $$$1\le l\le r\le 10^9$$$). It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, if there is no solution, print "NO" (without quotes). You can print letters in any case (upper or lower). Otherwise, print "YES" (without quotes). In the next line, print $$$n$$$ integers $$$a_1,a_2,\ldots,a_n$$$ — the array you construct. If there are multiple solutions, you may output any.

find l i
	| gcd l i == i 		= l
	| otherwise		= ($!) find (l + i -  (l `mod` i)) i

solve n l r
	| maximum a < (r+1) 		= "YES\n" ++ (printArr a) ++ "\n"
	| otherwise 			= "NO\n"
	where
		a =  ($!) map (find l) [1..n]
		printArr [] = " "
		printArr (x:xs) = show x ++ " " ++ printArr xs

exec 0 = pure ()
exec t = do
	(n:l:r:_) <- (map read . words) <$> getLine :: IO [Integer]
	putStr $ solve n l r
	exec (t-1)

main = do
	t <- read <$> getLine :: IO Int
	exec t

find l i
	| gcd l i == i 		= l
	| otherwise		= find (l + i -  (l `mod` i)) i

solve n l r
	-- | abs (r - l) < n-1	 	= "NO\n"
	| maximum a < (r+1) 		= "YES\n" ++ (printArr a) ++ "\n"
	| otherwise 			= "NO\n"
	where
		a =  map (find l) [1..n]
		printArr [] = " "
		printArr (x:xs) = show x ++ " " ++ printArr xs

exec 0 = pure ()
exec t = do
	(n:l:r:_) <- (map read . words) <$> getLine :: IO [Integer]
	putStr $ solve n l r
	exec (t-1)

main = do
	t <- read <$> getLine :: IO Int
	exec t

--
-- Michael V. Antosha
-- 2022
-- Michael.Antosha@gmail.com
--

{-# language Safe                      #-}
{-# language ImportQualifiedPost       #-}
{-# language NoMonomorphismRestriction #-}

{-# options_ghc -O3                              #-}

{-# options_ghc -Weverything                     #-}
{-# options_ghc -Werror                          #-}

{-# options_ghc -Wno-missing-import-lists        #-}
{-# options_ghc -Wno-missing-local-signatures    #-}

import Prelude               hiding (getLine)
import Control.Arrow
import Control.Monad
import Data.ByteString.Char8 qualified as B
import Data.Char
import Data.List             qualified as L

ri = readInts <$> B.getLine :: IO [Int]
  where
    readInts  = L.unfoldr ((second dropSpace <$>) . B.readInt) . dropSpace
    dropSpace = B.dropWhile isSpace

--showB False = "NO"
--showB True  = "YES"

main :: IO ()
main = do
    [t] <- ri
    tcs <- replicateM t $ do
        [n,l,r] <- ri
        return (n,l,r)
    mapM_ (putStr.showAns.solve) tcs

showAns Nothing   = unlines ["NO" ]
showAns (Just xs) = unlines ["YES", unwords . map show $ xs]

solve (n,l,r) | ok         = Just ans
              | otherwise  = Nothing
  where
    rs = map (range (l,r)) [1..n]
    ok = all (uncurry (<=)) rs
    ans = zipWith (*) [1..n] (map fst rs)

range (l,r) x = (   ((l-1)`div`x) + 1,
                    ( r   `div`x)    )

find l i
	| gcd l i == i 		= l
	| otherwise		= find (l + 1) i

solve n l r
	| abs (r - l) < n-1	 	= "NO\n"
	| maximum a < (r+1) 		= "YES\n" ++ (printArr a) ++ "\n"
	| otherwise 			= "NO\n"
	where
		a =  map (find l) [1..n]
		printArr [] = " "
		printArr (x:xs) = show x ++ " " ++ printArr xs

exec 0 = pure ()
exec t = do
	(n:l:r:_) <- (map read . words) <$> getLine :: IO [Integer]
	putStr $ solve n l r
	exec (t-1)

main = do
	t <- read <$> getLine :: IO Int
	exec t

find l i
	| gcd l i == i 		= l
	| otherwise		= find (l + i -  (l `mod` i)) i

solve n l r
	| abs (r - l) < n-1	 	= "NO\n"
	| maximum a < (r+1) 		= "YES\n" ++ (printArr a) ++ "\n"
	| otherwise 			= "NO\n"
	where
		a =  map (find l) [1..n]
		printArr [] = " "
		printArr (x:xs) = show x ++ " " ++ printArr xs

exec 0 = pure ()
exec t = do
	(n:l:r:_) <- (map read . words) <$> getLine :: IO [Integer]
	putStr $ solve n l r
	exec (t-1)

main = do
	t <- read <$> getLine :: IO Int
	exec t

find l i
	| gcd l i == i 		= l
	| otherwise		= find (l + i -  (l `mod` i)) i

solve n l r
	| abs (r - l) < n `div` 2 	= "NO\n"
	| maximum a < (r+1) 		= "YES\n" ++ (printArr a) ++ "\n"
	| otherwise 			= "NO\n"
	where
		a =  map (find l) [1..n]
		printArr [] = " "
		printArr (x:xs) = show x ++ " " ++ printArr xs

exec 0 = pure ()
exec t = do
	(n:l:r:_) <- (map read . words) <$> getLine :: IO [Integer]
	putStr $ solve n l r
	exec (t-1)

main = do
	t <- read <$> getLine :: IO Int
	exec t

find l i
	| gcd l i == i 		= l
	| otherwise		= find (l + i -  (l `mod` i)) i

solve n l r
	| abs (r - l) < n `div` 2 	= "NO1\n"
	| maximum a < (r+1) 		= "YES\n" ++ (printArr a) ++ "\n"
	| otherwise 			= "NO\n"
	where
		a =  map (find l) [1..n]
		printArr [] = " "
		printArr (x:xs) = show x ++ " " ++ printArr xs

exec 0 = pure ()
exec t = do
	(n:l:r:_) <- (map read . words) <$> getLine :: IO [Integer]
	putStr $ solve n l r
	exec (t-1)

main = do
	t <- read <$> getLine :: IO Int
	exec t