Despite his bad reputation, Captain Flint is a friendly person (at least, friendly to animals). Now Captain Flint is searching worthy sailors to join his new crew (solely for peaceful purposes). A sailor is considered as worthy if he can solve Flint's task.Recently, out of blue Captain Flint has been interested in math and even defined a new class of integers. Let's define a positive integer $$$x$$$ as nearly prime if it can be represented as $$$p \cdot q$$$, where $$$1 < p < q$$$ and $$$p$$$ and $$$q$$$ are prime numbers. For example, integers $$$6$$$ and $$$10$$$ are nearly primes (since $$$2 \cdot 3 = 6$$$ and $$$2 \cdot 5 = 10$$$), but integers $$$1$$$, $$$3$$$, $$$4$$$, $$$16$$$, $$$17$$$ or $$$44$$$ are not.Captain Flint guessed an integer $$$n$$$ and asked you: can you represent it as the sum of $$$4$$$ different positive integers where at least $$$3$$$ of them should be nearly prime.Uncle Bogdan easily solved the task and joined the crew. Can you do the same?

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Next $$$t$$$ lines contain test cases — one per line. The first and only line of each test case contains the single integer $$$n$$$ $$$(1 \le n \le 2 \cdot 10^5)$$$ — the number Flint guessed.

For each test case print:    YES and $$$4$$$ different positive integers such that at least $$$3$$$ of them are nearly prime and their sum is equal to $$$n$$$ (if there are multiple answers print any of them);  NO if there is no way to represent $$$n$$$ as the sum of $$$4$$$ different positive integers where at least $$$3$$$ of them are nearly prime.  YES NO

NoteIn the first and second test cases, it can be proven that there are no four different positive integers such that at least three of them are nearly prime.In the third test case, $$$n=31=2 \cdot 7 + 2 \cdot 5 + 2 \cdot 3 + 1$$$: integers $$$14$$$, $$$10$$$, $$$6$$$ are nearly prime.In the fourth test case, $$$n=36=5 + 2 \cdot 3 + 2 \cdot 5 + 3 \cdot 5$$$: integers $$$6$$$, $$$10$$$, $$$15$$$ are nearly prime.In the fifth test case, $$$n=44=2 \cdot 3 + 7 + 2 \cdot 5 + 3 \cdot 7$$$: integers $$$6$$$, $$$10$$$, $$$21$$$ are nearly prime.In the sixth test case, $$$n=100=2 + 2 \cdot 5 + 3 \cdot 11 + 5 \cdot 11$$$: integers $$$10$$$, $$$33$$$, $$$55$$$ are nearly prime.In the seventh test case, $$$n=258=2 \cdot 5 + 3 \cdot 7 + 13 \cdot 17 + 2 \cdot 3$$$: integers $$$10$$$, $$$21$$$, $$$221$$$, $$$6$$$ are nearly prime.

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

main = getLine >>= flip replicateM_ test . read

test = do
  n <- read <$> getLine
  if n > 30
    then
      if (n - 30) `notElem` [6, 10, 14]
        then putStrLn "YES" >> putStrLn ("6 10 14 " ++ show (n - 30))
        else putStrLn "YES" >> putStrLn ("6 10 15 " ++ show (n - 31))
    else putStrLn "NO"

import Data.Char
import Control.Monad
import Data.List

--6 10 14 15

answer x = if (x==36) then [6, 10, 15, 5]
           else if(x==40) then [6, 10, 15, 9]
           else if(x==44) then [6, 10, 15, 13]
           else [6, 10, 14, x-30]

get_ans h = if null h then ""
            else (show (head h)) ++ " " ++  (get_ans (tail h))

result x = if (x <= 30) then "NO"
           else "YES" ++ "\n" ++ ((get_ans . answer) x)

main = do
    tests <- getLine
    l <- getContents
    let l2 = words l
--    print l2
    let l3 = [ read w :: Int | w <- l2 ]
    let ans = [ result x | x <- l3]
    let ans2 = intercalate "\n" ans
    putStr ans2

import Data.Char
import Control.Monad
import Data.List

--6 10 14 15

answer 36 = [6, 10, 15, 5]
answer 40 = [6, 10, 15, 9]
answer 44 = [6, 10, 15, 13]
answer x = [6, 10, 14, x-30]

get_ans h = if null h then ""
            else (show (head h)) ++ " " ++  (get_ans (tail h))

result x = if (x <= 30) then "NO"
           else "YES" ++ "\n" ++ ((get_ans . answer) x)

main = do
    tests <- getLine
    l <- getContents
    let l2 = [ read w :: Int | w <- words l ]
    putStr(intercalate "\n" [result x | x <- l2])

import Control.Monad

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

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

putList :: (Show a) => [a] -> IO ()
putList = sequence_ . (map (\el -> putStr (show el) >> putChar ' '))

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

solve :: IO ()
solve = do
  n <- getOne :: IO Int
  let ans = countAns n
  if null ans then
    putStrLn "NO"
  else do
    putStrLn "YES"
    putList ans
    putChar '\n'

countAns :: (Ord a, Num a) => a -> [a]
countAns n
  | sum f3 >= n = []
  | n - sum f3 `elem` f3 = (n - sum f4) : f4
  | otherwise = (n - sum f3) : f3
  where
    f3 = [6, 10, 14]
    f4 = [6, 10, 15]

module Main where

   solve :: IO ()
   solve = do
       s <- getLine
       let n = read s :: Int
       putStrLn $ if n <= 30 then
           "NO"
       else if n `elem` [36, 40, 44] then
           "YES\n6 10 15 " ++ show (n - 31)
       else
           "YES\n6 10 14 " ++ show (n - 30)

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

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

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

onecase = do
		x<- read <$> getLine ::IO Int
		putStrLn $ if x<31  then "NO"
			   else if not(elem x [36,40,44])  then "YES\n"++ (intercalate " " (map show [14,10,6,x-30]))
							   else "YES\n"++ (intercalate " " (map show [15,10,6,x-31]))

main= do
		a<- read <$> getLine ::IO Int
		replicateM_ a onecase

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

main = getLine >>= flip replicateM_ test . read

test = do
  n <- read <$> getLine
  if n > 30
    then
      if (n - 30) `notElem` [6, 10, 14]
        then putStrLn "YES" >> putStrLn ("6 10 14 " ++ show (n - 30))
        else putStrLn "YES" >> putStrLn ("6 10 15 " ++ show (n - 30))
    else putStrLn "NO"

import Data.Char
import Control.Monad
import Data.List

--6 10 14 15

answer x = if (x==36) then [6, 10, 15, 5]
           else if(x==40) then [6, 10, 15, 9]
           else if(x==44) then [6, 10, 15, 13]
           else [6, 10, 14, x-30]

get_ans h = if null h then ""
            else (show (head h)) ++ " " ++  (get_ans (tail h))

result x = if (x <= 30) then "NO"
           else "YES" ++ "\n" ++ ((get_ans . answer) x)

main = do
    tests <- getLine
    l <- getContents
    let l2 = words l
    print l2
    let l3 = [ read w :: Int | w <- l2 ]
    let ans = [ result x | x <- l3]
    let ans2 = intercalate "\n" ans
    putStr ans2

module Main where

   solve :: IO ()
   solve = do
       s <- getLine
       let n = read s :: Int
       putStrLn $ if n <= 30 then
           "NO"
       else if n `elem` [36, 40, 44] then
           "YES\n6 10 15" ++ show (n - 31)
       else
           "YES\n6 10 14" ++ show (n - 30)

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

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

module Main where

   solve :: IO ()
   solve = do
       s <- getLine
       let n = read s :: Int
       putStrLn $ if n <= 30 then
           "NO"
       else if n `elem` [36, 40, 44] then
           "6 10 15" ++ show (n - 31)
       else
           "6 10 14" ++ show (n - 30)

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

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

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

onecase = do
		x<- read <$> getLine ::IO Int
		putStrLn $ if x<31  then "NO"
			   else if not(elem x [36,40,46])  then "YES\n"++ (intercalate " " (map show [14,10,6,x-30]))
							   else "YES\n"++ (intercalate " " (map show [15,10,6,x-31]))

main= do
		a<- read <$> getLine ::IO Int
		replicateM_ a onecase


Volodya has recently visited a very odd town. There are N tourist attractions in the town and every two of them are connected by a bidirectional road. Each road has some travel price (natural number) assigned to it and all prices are distinct. But the most striking thing about this town is that each city sightseeing tour has the same total price! That is, if we choose any city sightseeing tour — a cycle which visits every attraction exactly once — the sum of the costs of the tour roads is independent of the tour. Volodya is curious if you can find such price system with all road prices not greater than 1000.

Input contains just one natural number (3 ≤ N ≤ 20) — the number of town attractions.

Output should contain N rows containing N positive integer numbers each — the adjacency matrix of the prices graph (thus, j-th number in i-th row should be equal to the price of the road between the j-th and the i-th attraction). Diagonal numbers should be equal to zero. All numbers should not be greater than 1000. All prices should be positive and pairwise distinct. If there are several solutions, output any of them.

main = interact solve
solve input = output where
  n = read input :: Int
  nodes = [1,2,3,5,8,13,21,30,39,53,74,95,128,152,182,212,258,316,374,413]
  output = unlines [unwords [show $ edge i j|j<-[0..n-1]]|i<-[0..n-1]]
  edge x y = if x==y then 0 else nodes!!x + nodes!!y

import List
import Data.IntSet as Set
main = interact solve
solve input = output where
  n = read input :: Int
  nodes :: Int -> IntSet -> [Int] -> [[Int]]
  nodes 1 s _ = [[x]|x<-toList s]
  nodes x s xs = [y:ys|y<-toList s, ys<-nodes (x-1) (del0 s y xs) (y:xs)] where
    del0 s z zs = del (Set.delete z s) $
      concat [[u+v-z,z+u-v,z+v-u]|u<-zs, v<-zs, u<v, w<-s0]
    del :: IntSet -> [Int] -> IntSet
    del ys [] = ys
    del ys (z:zs) = Set.delete z $ del ys zs
    s0 = toList s
  table = head $ nodes n (fromList [1..1000]) []
  output = unlines [unwords [show $ edge i j|j<-[0..n-1]]|i<-[0..n-1]]
  edge x y = if x==y then 0 else table!!x + table!!y


Harry Water, Ronaldo, Her-my-oh-knee and their friends have started a new school year at their MDCS School of Speechcraft and Misery. At the time, they are very happy to have seen each other after a long time. The sun is shining, birds are singing, flowers are blooming, and their Potions class teacher, professor Snipe is sulky as usual. Due to his angst fueled by disappointment in his own life, he has given them a lot of homework in Potions class. Each of the n students has been assigned a single task. Some students do certain tasks faster than others. Thus, they want to redistribute the tasks so that each student still does exactly one task, and that all tasks are finished. Each student has their own laziness level, and each task has its own difficulty level. Professor Snipe is trying hard to improve their work ethics, so each student’s laziness level is equal to their task’s difficulty level. Both sets of values are given by the sequence a, where ai represents both the laziness level of the i-th student and the difficulty of his task. The time a student needs to finish a task is equal to the product of their laziness level and the task’s difficulty. They are wondering, what is the minimum possible total time they must spend to finish all tasks if they distribute them in the optimal way. Each person should receive one task and each task should be given to one person. Print the answer modulo 10 007.

The first line of input contains integer n (1 ≤ n ≤ 100 000) — the number of tasks. The next n lines contain exactly one integer number ai (1 ≤ ai ≤ 100 000) — both the difficulty of the initial task and the laziness of the i-th students.

Print the minimum total time to finish all tasks modulo 10 007.

NoteIn the first sample, if the students switch their tasks, they will be able to finish them in 3 + 3 = 6 time units.

import Data.List
main = interact $ show . (`rem` 10007) . sum . solve . map read . tail . words
solve l = let s = sort l in zipWith (*) s (reverse s)

import Data.List
main = interact $ show . (`rem` 10007) . sum . solve . map read . tail . words
solve l = zipWith (*) l (sort l)

import Data.List
main = interact $ show . (`rem` 10007) . sum . solve . map read . words
solve l = zipWith (*) l (sort l)


City X consists of n vertical and n horizontal infinite roads, forming n × n intersections. Roads (both vertical and horizontal) are numbered from 1 to n, and the intersections are indicated by the numbers of the roads that form them.Sand roads have long been recognized out of date, so the decision was made to asphalt them. To do this, a team of workers was hired and a schedule of work was made, according to which the intersections should be asphalted.Road repairs are planned for n2 days. On the i-th day of the team arrives at the i-th intersection in the list and if none of the two roads that form the intersection were already asphalted they asphalt both roads. Otherwise, the team leaves the intersection, without doing anything with the roads.According to the schedule of road works tell in which days at least one road will be asphalted.

The first line contains integer n (1 ≤ n ≤ 50) — the number of vertical and horizontal roads in the city.  Next n2 lines contain the order of intersections in the schedule. The i-th of them contains two numbers hi, vi (1 ≤ hi, vi ≤ n), separated by a space, and meaning that the intersection that goes i-th in the timetable is at the intersection of the hi-th horizontal and vi-th vertical roads. It is guaranteed that all the intersections in the timetable are distinct.

In the single line print the numbers of the days when road works will be in progress in ascending order. The days are numbered starting from 1.

NoteIn the sample the brigade acts like that:  On the first day the brigade comes to the intersection of the 1-st horizontal and the 1-st vertical road. As none of them has been asphalted, the workers asphalt the 1-st vertical and the 1-st horizontal road;  On the second day the brigade of the workers comes to the intersection of the 1-st horizontal and the 2-nd vertical road. The 2-nd vertical road hasn't been asphalted, but as the 1-st horizontal road has been asphalted on the first day, the workers leave and do not asphalt anything;  On the third day the brigade of the workers come to the intersection of the 2-nd horizontal and the 1-st vertical road. The 2-nd horizontal road hasn't been asphalted but as the 1-st vertical road has been asphalted on the first day, the workers leave and do not asphalt anything;  On the fourth day the brigade come to the intersection formed by the intersection of the 2-nd horizontal and 2-nd vertical road. As none of them has been asphalted, the workers asphalt the 2-nd vertical and the 2-nd horizontal road.

import Data.List
import qualified Data.Set as Set

main :: IO()
main = putStrLn . intercalate " " . map show . solve 1 Set.empty Set.empty . map read . tail . words =<< getContents

solve :: Int -> Set.Set Int -> Set.Set Int -> [Int] -> [Int]
solve _ _ _ [] = []
solve i h v (x:y:s) | (Set.member x h) || (Set.member y v) = solve (i + 1) h v s
                    | otherwise = i : solve (i + 1) (Set.insert x h) (Set.insert y v) s

import Control.Monad
import Data.Set (empty,insert,member)
main :: IO()
main = do
    n <- readLn :: IO Int
    a <- forM [1..(n*n)] $ \_ -> do
        [x,y] <- fmap ((map read) . words) getLine :: IO [Int]
        return (x,y)
    mapM_ (\x -> putStr ((show x)++" ")) (solve 1 a empty empty)

solve _ [] _ _ = []
solve i ((x,y):xs) mh mv
 |or [member x mh,member y mv] = solve (i+1) xs mh mv
 |otherwise = i:solve (i+1) xs (insert x mh) (insert y mv)

{-# LANGUAGE FlexibleContexts, ScopedTypeVariables, BangPatterns #-}
{-# OPTIONS_GHC -O2 #-}

import Control.Applicative
import Control.Monad hiding ((<$!>))
import Control.Monad.ST.Safe
import Control.Monad.State hiding ((<$!>))
import Data.Array
-- import Data.Array.IArray
import Data.Array.IO.Safe
import Data.Array.MArray.Safe
import Data.Array.ST.Safe
-- import Data.Array.Unboxed
import qualified Data.ByteString.Char8 as B
import qualified Data.ByteString.Lazy.Builder as BB
import Data.Char
import qualified Data.Foldable as F
import Data.Function
import Data.Graph
import Data.Int
import Data.List
import Data.List.Split
import Data.Maybe
import Data.Monoid
import Data.Ratio
import qualified Data.Sequence as Seq
import Data.Sequence (Seq)
import Data.Set (Set)
import qualified Data.Set as Set
import Data.IntSet (IntSet)
import qualified Data.IntSet as IntSet
-- import Data.Tree
import Data.Tuple
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.HashMap.Strict (HashMap)
import qualified Data.HashMap.Strict as HashMap
import Data.IntMap (IntMap)
import qualified Data.IntMap as IntMap
-- import Debug.Trace
import System.IO

-- getInts = fmap (map read . words) getLine
getInts = unfoldr (B.readInt . B.dropWhile isSpace) <$> B.getLine

main = do
  n <- readLn
  ijs <- replicateM (n^2) getInts

  let
    rs = snd $ mapAccumL f ([], []) $ zip ijs [1..]
      where
        f (is, js) ([i, j], k)
          | i `elem` is || j `elem` js = ((is, js), 0)
          | otherwise = ((i:is, j:js), k)

  putStrLn $ unwords $ map show $ filter (/= 0) rs

import Data.Set hiding (map)

main = interact $ solver

into_pairs [] = []
into_pairs (h:v:t) = (h, v) : into_pairs t

solver str = unwords $ map show res where
             ws = words str
             (_: list) = ws
             order = into_pairs $ map (read :: String->Int) list
             res = solve order empty empty 1

solve [] _ _ _ = []
solve ((h, v) : t) removedHorizontal removedVertical i =
         if member h removedHorizontal || member v removedVertical
         then solve t removedHorizontal removedVertical (i + 1)
         else i : solve t (insert h removedHorizontal) (insert v removedVertical) (i + 1)

import Control.Applicative
f xl yl [] sch n m= []
f xl yl (schx:schxs) (schy:schys) n m| n == 0 = []
                                     | (elem schx xl) || (elem schy yl) = f xl yl schxs schys n (m+1)
                                     | otherwise = (m+1):(f (schx:xl) (schy:yl) schxs schys (n-1) (m+1))
toTup a = ((w !! 0),(w !! 1))
  where w = [read n::Int|n <- (words a)]
main = do
  n <- (read::String ->Int) <$> getLine
  (xl,yl) <- unzip.(map toTup).lines <$> getContents
  putStrLn $ unwords $ map show $ f [] [] xl yl n 0

import Data.List
import Data.Tree
import Data.Int
import Data.Maybe
import Data.Char
import Data.Functor
import Data.Function
import Data.Ord
import Data.Bits
import Data.Monoid
import Control.Monad
import Control.Monad.ST.Safe
import Control.Arrow
import Data.Array
import Data.Array.ST.Safe
import Data.Array.Unboxed as UA
import Data.STRef
import qualified Data.Map as Map
import qualified Data.Set as Set
import qualified Data.ByteString.Char8 as C
main= someFunc
rIn x= fst $ fromJust  $ C.readInt x
someFunc::IO()
someFunc = C.getLine>>= (\(n) ->solve=<<forM [1..(rIn n)^2] (\i->map rIn.C.words <$>C.getLine) )
solve xs= putStrLn $ unwords $ map show $ reverse $ foldl (\ bs (c,(a,_)) ->if a then c:bs else bs)[] $ zip [0..] $ scanl (slv1) (False,[Set.empty,Set.empty]) xs
slv1 (_,[s1,s2]) [x,y]= if Set.member x s1 || Set.member y s2 then (False, [s1,s2]) else (True,[Set.insert x s1,Set.insert y s2])

-- Codeforces 583A

import Control.Monad
import qualified Data.Set as Set
import Data.List (intercalate)

main :: IO ()
main = do
    n <- fmap read getLine :: IO Int
    getContents >>= putStrLn . intercalate " " . map show . solve 1 (Set.empty, Set.empty) . map read . words

solve :: Int -> (Set.Set Int, Set.Set Int) -> [Int] -> [Int]
solve _ _ [] = []
solve d (h, v) (i:j:xs)
    | (Set.member i h) || (Set.member j v) = solve (d+1) (h, v) xs
    | otherwise = d : solve (d+1) (Set.insert i h, Set.insert j v) xs

import Control.Applicative
import Data.List

process _ [] [] _ _ = putStrLn ""
process i (a:as) (b:bs) c d | elem a c || elem b d = process (i+1) as bs c d
                            | otherwise = do
                                            putStr (show i ++" ")
                                            process (i+1) as bs (a:c) (b:d)

main::IO ()
main=do
    n<- read <$> getLine::IO Int
    [a1,a2]<- transpose <$> map(map read) <$> map words <$> lines <$> getContents :: IO [[Int]]
    process 1 a1 a2 [] []

import Data.List (mapAccumL)
import Data.Maybe (catMaybes)

main :: IO ()
main = putStrLn . unwords . map show . solve . map (map read . words) . tail . lines =<< getContents

solve :: [[Int]] -> [Int]
solve = catMaybes . snd . mapAccumL f ([], [], 1)
  where f (xs, ys, t) [x, y]
          | x `elem` xs || y `elem` ys = ((xs, ys, t + 1), Nothing)
          | otherwise = ((x:xs, y:ys, t + 1), Just t)
        f _ _ = undefined

import Data.Bits (setBit,testBit)
import Data.Word (Word64)
main = do
  n <- readLn
  putStrLn . unwords . map show =<< solve (0 :: Word64,0 :: Word64) [1..n^2]
solve _ [] = return []
solve (h,v) (i:is) = do
  [a,b] <- fmap (map read . words) getLine
  if (h `testBit` a) || (v `testBit` b)
    then solve (h,v) is
    else fmap (i:) $ solve (h `setBit` a, v `setBit` b) is

import Control.Applicative
import Data.List
import qualified Data.ByteString.Char8 as C
import Data.Maybe
import qualified Data.Set as S

process _ _ _ [] x = reverse x
process d h v (a:b:c) x | S.notMember a h  && S.notMember b v = process (d+1) (S.insert a h) (S.insert b v) c (d:x)
	                | otherwise = process (d+1) h v c x

main=do
	n<- read <$> getLine::IO Int
	s<-map (fst.fromJust.C.readInt). C.words<$> C.getContents::IO [Int]
	putStrLn $ intercalate " " $ map show $ process 1 S.empty S.empty s []

{-# LANGUAGE FlexibleInstances #-}
module Main (printShit, printShitV, readShit, main) where
import Control.Monad.State
import Data.Set
-- Meat

solve :: [[Int]] -> [Int]
solve as = [ snd x | x <- bools `zip` [1..], fst x]
    where bools = evalState (mapM feed as) noHistory

data RoadHistory = RoadHistory (Set Int) (Set Int) deriving (Show)

noHistory :: RoadHistory
noHistory = RoadHistory Data.Set.empty Data.Set.empty

feed :: [Int] -> State RoadHistory Bool
feed (h:v:_ )= state $ transform h v
feed _ = error "You suck"

transform :: Int -> Int -> RoadHistory -> (Bool, RoadHistory)
transform h v (RoadHistory horH verH) = (shouldWork, RoadHistory newHorH newVerH)
    where shouldWork = h `notMember` horH && v `notMember` verH
          newHorH = if shouldWork then insert h horH else horH
          newVerH = if shouldWork then insert v verH else verH

-- Shit
main :: IO ()
main = do
        _:as <- readShit
        printShit $ solve as

class Shit a where
    printShit :: a -> IO ()
    printShitV :: a -> IO ()
    readShit :: IO a
    printShitV = printShit

instance  Shit [Int] where
    printShit = putStrLn . unwords . fmap show
    printShitV = putStrLn . unlines . fmap show
    readShit = fmap (fmap read . words) getLine

instance Shit [[Int]] where
    printShit = putStrLn . unlines . fmap (unwords . fmap show)
    readShit = fmap (fmap (fmap read . words) . lines) getContents

import Control.Monad
import Data.Set (empty,insert,member)
main :: IO()
main = do
    n <- readLn :: IO Int
    a <- forM [1..(n*n)] $ \_ -> do
        [x,y] <- fmap ((map read) . words) getLine :: IO [Int]
        return (x,y)
    mapM_ (\x -> putStr ((show x)++" ")) (solve 1 a empty empty)

solve _ [] _ _ = []
solve i ((x,y):xs) mh mv
 |or [member x mh,member y mv] = solve (i+1) xs mh mv
 |otherwise = i:solve (i+1) xs (insert x mh) (insert x mv)

import Control.Monad
main :: IO()
main = do
    n <- readLn :: IO Int
    a <- forM [1..(n*n)] $ \_ -> do
        [x,y] <- fmap ((map read) . words) getLine :: IO [Int]
        return (x,y)
    mapM_ (\x -> putStr ((show x)++" ")) (solve 1 a)

solve _ [] = []
solve i ((x,y):xs)
 |x==y = i:solve (i+1) xs
 |otherwise = solve (i+1) xs

import Control.Monad
main :: IO()
main = do
    n <- readLn :: IO Int
    a <- forM [1..(n*n)] $ \_ -> do
        [x,y] <- fmap ((map read) . words) getLine :: IO [Int]
        return (x,y)
    mapM_ (\x -> putStr ((show x)++" ")) (solve 1 a)
    putStrLn ""

solve _ [] = []
solve i ((x,y):xs)
 |x==y = i:solve (i+1) xs
 |otherwise = solve (i+1) xs

import Control.Monad
import Data.Set (empty,insert,member)
main :: IO()
main = do
    n <- readLn :: IO Int
    a <- forM [1..(n*n)] $ \_ -> do
        [x,y] <- fmap ((map read) . words) getLine :: IO [Int]
        return (x,y)
    mapM_ (\x -> putStr ((show x)++" ")) (solve 1 a empty)

solve _ [] _ = []
solve i ((x,y):xs) m
 |or [member x m,member y m] = solve (i+1) xs m
 |otherwise = i:solve (i+1) xs (insert x . insert y $ m)

import Control.Applicative
import Data.List

main::IO ()
main=do
    n<- read <$> getLine::IO Int
    putStrLn $ intercalate " " $ map show [i*i|i<-[1..n]]

import Data.Bits (setBit,testBit)
import Control.Monad (when,foldM_)
main = do
  n <- readLn
  foldM_ solve (0 :: Int,0 :: Int) [1..n]
solve (h,v) i = do
  [a,b] <- fmap (map read . words) getLine
  when ((not (h `testBit` a)) && (not (v `testBit` b))) (print i)
  return (h `setBit` a, v `setBit` b)

import Data.Bits (setBit,testBit)
main = do
  n <- readLn
  putStrLn . unwords . map show =<< solve (0 :: Int,0 :: Int) [1..n^2]
solve _ [] = return []
solve (h,v) (i:is) = do
  [a,b] <- fmap (map read . words) getLine
  if (h `testBit` a) || (v `testBit` b)
    then solve (h,v) is
    else fmap (i:) $ solve (h `setBit` a, v `setBit` b) is

{-# LANGUAGE FlexibleInstances #-}
module Main (printShit, printShitV, readShit, main) where
import Control.Monad.State
import Data.Set
-- Meat

solve :: [[Int]] -> [Int]
solve as = [ snd x | x <- bools `zip` [1..], fst x]
    where bools = evalState (mapM feed as) noHistory

data RoadHistory = RoadHistory (Set Int) (Set Int) deriving (Show)

noHistory :: RoadHistory
noHistory = RoadHistory Data.Set.empty Data.Set.empty

feed :: [Int] -> State RoadHistory Bool
feed (h:v:_ )= state $ transform h v
feed _ = error "You suck"

transform :: Int -> Int -> RoadHistory -> (Bool, RoadHistory)
transform h v (RoadHistory horH verH) = (shouldWork, RoadHistory newHorH newVerH)
    where shouldWork = h `notMember` horH && v `notMember` verH
          newHorH = if shouldWork then insert h horH else horH
          newVerH = if shouldWork then insert v horH else verH

-- Shit
main :: IO ()
main = do
        _:as <- readShit
        printShit $ solve as

class Shit a where
    printShit :: a -> IO ()
    printShitV :: a -> IO ()
    readShit :: IO a
    printShitV = printShit

instance  Shit [Int] where
    printShit = putStrLn . unwords . fmap show
    printShitV = putStrLn . unlines . fmap show
    readShit = fmap (fmap read . words) getLine

instance Shit [[Int]] where
    printShit = putStrLn . unlines . fmap (unwords . fmap show)
    readShit = fmap (fmap (fmap read . words) . lines) getContents


It seems that Borya is seriously sick. He is going visit n doctors to find out the exact diagnosis. Each of the doctors needs the information about all previous visits, so Borya has to visit them in the prescribed order (i.e. Borya should first visit doctor 1, then doctor 2, then doctor 3 and so on). Borya will get the information about his health from the last doctor.Doctors have a strange working schedule. The doctor i goes to work on the si-th day and works every di day. So, he works on days si, si + di, si + 2di, ....The doctor's appointment takes quite a long time, so Borya can not see more than one doctor per day. What is the minimum time he needs to visit all doctors?

First line contains an integer n — number of doctors (1 ≤ n ≤ 1000).  Next n lines contain two numbers si and di (1 ≤ si, di ≤ 1000).

Output a single integer — the minimum day at which Borya can visit the last doctor.

NoteIn the first sample case, Borya can visit all doctors on days 2, 3 and 4.In the second sample case, Borya can visit all doctors on days 10 and 11.

main = getContents >>= print . exec
exec = solve 0 . map read . tail . words
solve m (s:d:xs) = solve (s + k * d) xs
  where k = max 0 $ ceiling $ fromIntegral (m + 1 - s) / fromIntegral d
solve m _ = m

module Main (main) where

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

main :: IO ()
main = do
    n <- readLn
    xs <- map (map readInt.words) <$> replicateM n getLine
    let ans = solve xs
    print ans

readInt :: String -> Int
readInt = read

solve :: [[Int]] -> Int
solve = foldl update 0

update :: Int -> [Int] -> Int
update s (a:b:_) = fromJust $ find (> s) [a + d * b | d <- [0..]]

main = getContents >>= print . exec
exec = solve 0 . map read . tail . words
solve m (s:d:xs) = solve (s + k * d) xs
  where k = max 0 $ ceiling $ fromIntegral (m - s) / fromIntegral d
solve m _ = m


There is a famous olympiad, which has more than a hundred participants. The Olympiad consists of two stages: the elimination stage, and the final stage. At least a hundred participants will advance to the final stage. The elimination stage in turn consists of two contests.A result of the elimination stage is the total score in two contests, but, unfortunately, the jury lost the final standings and has only standings for the first and for the second contest separately. In each contest, the participants are ranked by their point score in non-increasing order. When two participants have a tie (earned the same score), they are ranked by their passport number (in accordance with local regulations, all passport numbers are distinct). In the first contest, the participant on the 100-th place scored $$$a$$$ points. Also, the jury checked all participants from the 1-st to the 100-th place (inclusive) in the first contest and found out that all of them have at least $$$b$$$ points in the second contest.Similarly, for the second contest, the participant on the 100-th place has $$$c$$$ points. And the jury checked that all the participants from the 1-st to the 100-th place (inclusive) have at least $$$d$$$ points in the first contest.After two contests, all participants are ranked by their total score in two contests in non-increasing order. When participants have the same total score, tie-breaking with passport numbers is used. The cutoff score to qualify to the final stage is the total score of the participant on the 100-th place.Given integers $$$a$$$, $$$b$$$, $$$c$$$, $$$d$$$, please help the jury determine the smallest possible value of the cutoff score.

You need to process $$$t$$$ test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 3025$$$) — the number of test cases. Then descriptions of $$$t$$$ test cases follow. The first line of each test case contains four integers $$$a$$$, $$$b$$$, $$$c$$$, $$$d$$$ ($$$0 \le a,\,b,\,c,\,d \le 9$$$; $$$d \leq a$$$; $$$b \leq c$$$).  One can show that for any test case satisfying the constraints above, there is at least one olympiad scenario possible.

For each test case print a single integer — the smallest possible cutoff score in some olympiad scenario satisfying the given information.

NoteFor the first test case, consider the following olympiad scenario: there are $$$101$$$ participants in the elimination stage, each having $$$1$$$ point for the first contest and $$$2$$$ points for the second contest. Hence the total score of the participant on the 100-th place is $$$3$$$.For the second test case, consider the following olympiad scenario:   there are $$$50$$$ participants with points $$$5$$$ and $$$9$$$ for the first and second contest respectively;  $$$50$$$ participants with points $$$4$$$ and $$$8$$$ for the first and second contest respectively;  and $$$50$$$ participants with points $$$2$$$ and $$$9$$$ for the first and second contest respectively.  Hence the total point score of the participant on the 100-th place is $$$12$$$.

import Control.Arrow ((>>>))

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

solve :: [Int] -> Int
solve [a, b, c, d] = max (a + b) (c + d)


Very soon there will be a parade of victory over alien invaders in Berland. Unfortunately, all soldiers died in the war and now the army consists of entirely new recruits, many of whom do not even know from which leg they should begin to march. The civilian population also poorly understands from which leg recruits begin to march, so it is only important how many soldiers march in step.There will be n columns participating in the parade, the i-th column consists of li soldiers, who start to march from left leg, and ri soldiers, who start to march from right leg.The beauty of the parade is calculated by the following formula: if L is the total number of soldiers on the parade who start to march from the left leg, and R is the total number of soldiers on the parade who start to march from the right leg, so the beauty will equal |L - R|.No more than once you can choose one column and tell all the soldiers in this column to switch starting leg, i.e. everyone in this columns who starts the march from left leg will now start it from right leg, and vice versa. Formally, you can pick no more than one index i and swap values li and ri. Find the index of the column, such that switching the starting leg for soldiers in it will maximize the the beauty of the parade, or determine, that no such operation can increase the current beauty.

The first line contains single integer n (1 ≤ n ≤ 105) — the number of columns.  The next n lines contain the pairs of integers li and ri (1 ≤ li, ri ≤ 500) — the number of soldiers in the i-th column which start to march from the left or the right leg respectively.

Print single integer k — the number of the column in which soldiers need to change the leg from which they start to march, or 0 if the maximum beauty is already reached. Consider that columns are numbered from 1 to n in the order they are given in the input data. If there are several answers, print any of them.

NoteIn the first example if you don't give the order to change the leg, the number of soldiers, who start to march from the left leg, would equal 5 + 8 + 10 = 23, and from the right leg — 6 + 9 + 3 = 18. In this case the beauty of the parade will equal |23 - 18| = 5.If you give the order to change the leg to the third column, so the number of soldiers, who march from the left leg, will equal 5 + 8 + 3 = 16, and who march from the right leg — 6 + 9 + 10 = 25. In this case the beauty equals |16 - 25| = 9.It is impossible to reach greater beauty by giving another orders. Thus, the maximum beauty that can be achieved is 9.

import Data.Ord
import Data.List
main = interact $ show . solve . pairs . map read . tail . words
pairs (a:b:xs) = (a,b) : pairs xs
pairs [] = []
solve lrs | m < update (0,0) = 0
          | otherwise = i
  where (m,i) = maximum $ flip zip [1..] $ map update lrs
        (ls,rs) = unzip lrs
        update (l,r) = abs ((sum ls + r - l) - (sum rs + l - r))

{-
module Main where
  import Data.List
  import Control.Monad
  import Data.Array
  import qualified Data.Set as S

  toArray :: [a] -> Array Int a
  toArray xs =
    let ls = length xs - 1
        in array (0, ls) $ zip [0..ls] xs

  readInt :: String -> Int
  readInt s = read s :: Int

  readMultilineInput :: Int -> (String -> IO a) -> IO [a]
  readMultilineInput n transformer = replicateM n (getLine >>= transformer)

  elemSet :: (Ord a) => a -> S.Set a -> Bool
  elemSet elem sets =
    let found = elem `S.lookupIndex` sets
        in toBool found
        where
          toBool :: Maybe Int -> Bool
          toBool (Just _) = True
          toBool Nothing = False

  currentValue :: [(Int, Int)] -> Int
  currentValue xs =
    let (ps, qs) = unzip xs
        in (sum ps) - (sum qs)

  parseTuple :: String -> (Int, Int)
  parseTuple xs =
    let [x, y] = (map readInt . words) xs
        in (x, y)

  changes :: Int -> (Int, Int) -> Int
  changes current (l, r) = current + 2 * (r - l)

  indexOfMostValue :: Int -> Int -> Int -> [Int] -> Int
  indexOfMostValue midx _ _ [] = midx
  indexOfMostValue midx most idx (x:xs)
    | abs most < abs x = indexOfMostValue idx (abs x) (idx + 1) xs
    | otherwise = indexOfMostValue midx most (idx + 1) xs

  main :: IO()
  main = do
    n <- getLine >>= return . readInt
    xs <- readMultilineInput n (return . parseTuple)
    let cv = currentValue xs
        chgs = map (changes cv) xs
    print $ (1+) $ indexOfMostValue (-1) (abs cv) 0 chgs
-}
import Control.Monad
import Data.Array
import Data.List
import Data.Ord
test :: Int -> Int
test n = n
parseInts :: String -> [Int]
parseInts str = map read (words str)
toArray :: [a] -> Array Int a
toArray xs =
  let ls = length xs - 1
    in array (0, ls) $ zip [0..ls] xs
toTuple :: [a] -> (a, a)
toTuple (a : b : _) = (a,b)
solve :: [(Int, Int)] -> Int
solve xs =
  let diff = sum $ map (\(a, b) -> a - b) xs
      trans = map (\(a, b) -> diff + 2 * (b - a)) xs
      in snd $ maximumBy (comparing fst) (zip (map abs (diff:trans)) [0..])

main :: IO ()
main = do
  (n : _) <- getLine >>= return . parseInts
  arr <- replicateM n (getLine >>= return . toTuple . parseInts)
  print $ solve arr

import Control.Monad
import Data.Array
import Data.List
import Data.Ord
parseInts :: String -> [Int]
parseInts str = map read (words str)
toTuple :: [a] -> (a, a)
toTuple (a : b : _) = (a,b)
solve :: [(Int, Int)] -> Int
solve xs =
  let diff = sum $ map (\(a, b) -> a - b) xs
      trans = map (\(a, b) -> diff + 2 * (b - a)) xs
      in snd $ maximumBy (comparing fst) (zip (map abs (diff:trans)) [0..])
{-fuck-}
main :: IO ()
main = do
  (n : _) <- getLine >>= return . parseInts
  arr <- replicateM n (getLine >>= return . toTuple . parseInts)
  print $ solve arr

{-
module Main where
  import Data.List
  import Control.Monad
  import Data.Array
  import qualified Data.Set as S

  toArray :: [a] -> Array Int a
  toArray xs =
    let ls = length xs - 1
        in array (0, ls) $ zip [0..ls] xs

  readInt :: String -> Int
  readInt s = read s :: Int

  readMultilineInput :: Int -> (String -> IO a) -> IO [a]
  readMultilineInput n transformer = replicateM n (getLine >>= transformer)

  elemSet :: (Ord a) => a -> S.Set a -> Bool
  elemSet elem sets =
    let found = elem `S.lookupIndex` sets
        in toBool found
        where
          toBool :: Maybe Int -> Bool
          toBool (Just _) = True
          toBool Nothing = False

  currentValue :: [(Int, Int)] -> Int
  currentValue xs =
    let (ps, qs) = unzip xs
        in (sum ps) - (sum qs)

  parseTuple :: String -> (Int, Int)
  parseTuple xs =
    let [x, y] = (map readInt . words) xs
        in (x, y)

  changes :: Int -> (Int, Int) -> Int
  changes current (l, r) = current + 2 * (r - l)

  indexOfMostValue :: Int -> Int -> Int -> [Int] -> Int
  indexOfMostValue midx _ _ [] = midx
  indexOfMostValue midx most idx (x:xs)
    | abs most < abs x = indexOfMostValue idx (abs x) (idx + 1) xs
    | otherwise = indexOfMostValue midx most (idx + 1) xs

  main :: IO()
  main = do
    n <- getLine >>= return . readInt
    xs <- readMultilineInput n (return . parseTuple)
    let cv = currentValue xs
        chgs = map (changes cv) xs
    print $ (1+) $ indexOfMostValue (-1) (abs cv) 0 chgs
-}
import Control.Monad
import Data.Array
import Data.List
import Data.Ord
test :: Int -> Int
test n = n
parseInts :: String -> [Int]
parseInts str = map read (words str)
toArray :: [a] -> Array Int a
toArray xs =
  let ls = length xs - 1
    in array (0, ls) $ zip [0..ls] xs
toTuple :: [a] -> (a, a)
toTuple (a : b : _) = (a,b)
solve :: [(Int, Int)] -> Int
solve xs =
  let diff = sum $ map (\(a, b) -> a - b) xs
      trans = map (\(a, b) -> abs $ diff + 2 * (b - a)) xs
      in snd $ minimumBy (comparing fst) (zip (diff:trans) [0..])

main :: IO ()
main = do
  (n : _) <- getLine >>= return . parseInts
  arr <- replicateM n (getLine >>= return . toTuple . parseInts)
  print $ solve arr

import Control.Monad
import Data.Array
import Data.List
import Data.Ord
parseInts :: String -> [Int]
parseInts str = map read (words str)
toTuple :: [a] -> (a, a)
toTuple (a : b : _) = (a,b)
solve :: [(Int, Int)] -> Int
solve xs =
  let diff = sum $ map (\(a, b) -> a - b) xs
      trans = map (\(a, b) -> diff - (a - b) + (b - a)) xs
      in snd $ minimumBy (comparing fst) (zip (diff:trans) [0..])

main :: IO ()
main = do
  (n : _) <- getLine >>= return . parseInts
  arr <- replicateM n (getLine >>= return . toTuple . parseInts)
  print $ solve arr

module Main where
  import Data.List
  import Control.Monad
  import Data.Array
  import qualified Data.Set as S

  toArray :: [a] -> Array Int a
  toArray xs =
    let ls = length xs - 1
        in array (0, ls) $ zip [0..ls] xs

  readInt :: String -> Int
  readInt s = read s :: Int

  readMultilineInput :: Int -> (String -> IO a) -> IO [a]
  readMultilineInput n transformer = replicateM n (getLine >>= transformer)

  elemSet :: (Ord a) => a -> S.Set a -> Bool
  elemSet elem sets =
    let found = elem `S.lookupIndex` sets
        in toBool found
        where
          toBool :: Maybe Int -> Bool
          toBool (Just _) = True
          toBool Nothing = False

  currentValue :: [(Int, Int)] -> Int
  currentValue xs =
    let (ps, qs) = unzip xs
        in (sum ps) - (sum qs)

  parseTuple :: String -> (Int, Int)
  parseTuple xs =
    let [x, y] = (map readInt . words) xs
        in (x, y)

  changes :: Int -> (Int, Int) -> Int
  changes current (l, r) = current + 2 * (r - l)

  indexOfMostValue :: Int -> Int -> Int -> [Int] -> Int
  indexOfMostValue midx _ _ [] = midx
  indexOfMostValue midx most idx (x:xs)
    | abs most < abs x = indexOfMostValue idx (abs x) (idx + 1) xs
    | otherwise = indexOfMostValue midx most (idx + 1) xs

  main :: IO()
  main = do
    n <- getLine >>= return . readInt
    xs <- readMultilineInput n (return . parseTuple)
    let cv = currentValue xs
        chgs = map (changes cv) xs
    print $ (1+) $ indexOfMostValue (-1) 0 0 chgs


Let's define a multiplication operation between a string $$$a$$$ and a positive integer $$$x$$$: $$$a \cdot x$$$ is the string that is a result of writing $$$x$$$ copies of $$$a$$$ one after another. For example, "abc" $$$\cdot~2~=$$$ "abcabc", "a" $$$\cdot~5~=$$$ "aaaaa".A string $$$a$$$ is divisible by another string $$$b$$$ if there exists an integer $$$x$$$ such that $$$b \cdot x = a$$$. For example, "abababab" is divisible by "ab", but is not divisible by "ababab" or "aa".LCM of two strings $$$s$$$ and $$$t$$$ (defined as $$$LCM(s, t)$$$) is the shortest non-empty string that is divisible by both $$$s$$$ and $$$t$$$.You are given two strings $$$s$$$ and $$$t$$$. Find $$$LCM(s, t)$$$ or report that it does not exist. It can be shown that if $$$LCM(s, t)$$$ exists, it is unique.

The first line contains one integer $$$q$$$ ($$$1 \le q \le 2000$$$) — the number of test cases. Each test case consists of two lines, containing strings $$$s$$$ and $$$t$$$ ($$$1 \le |s|, |t| \le 20$$$). Each character in each of these strings is either 'a' or 'b'.

For each test case, print $$$LCM(s, t)$$$ if it exists; otherwise, print -1. It can be shown that if $$$LCM(s, t)$$$ exists, it is unique.

NoteIn the first test case, "baba" = "baba" $$$\cdot~1~=$$$ "ba" $$$\cdot~2$$$.In the second test case, "aaaaaa" = "aa" $$$\cdot~3~=$$$ "aaa" $$$\cdot~2$$$.

readString :: () -> (IO[Char])
readString () = do
    c <- getChar

    if (c==' ' || c=='\n')
        then return [c]
    else
        do
            rest <- readString()
            return ([c]++rest)

readInt :: () -> IO Int
readInt () = do
    help <- readString()
    let x = read help :: Int

    return x

printer :: () -> IO()
printer () = do
    putStr "1\n"
    printer()

isSignleCharacter :: (String) -> (Bool)
isSignleCharacter (s) = ((replicate (length s) (s!!0))==s)

cpyString :: (Int, String) -> (String)
cpyString (0, s) = ""
cpyString (cnt, s) = s++cpyString(cnt-1, s)

isDivisible :: (String, String) -> (Bool)
isDivisible (pattern, txt) = (cpyString((length txt) `div` length (pattern), pattern)==txt)

solveTestcase :: (Int) -> IO()
solveTestcase 0 = return ()
solveTestcase (testId) = do
    s <- getLine
    t <- getLine

    let solutions1 = [cpyString(cnt, s) | cnt <- [1..20], isDivisible(t, cpyString(cnt, s))]
    let solutions2 = [cpyString(cnt, t) | cnt <- [1..20], isDivisible(s, cpyString(cnt, t))]

    putStrLn ((solutions1++solutions2++["-1"])!!0)
    solveTestcase(testId-1)

main = do
    t <- readInt()
    solveTestcase(t)

module Main where
import Data.Foldable (traverse_)
import Data.List (sort)

duplicate :: Int ->  String -> String
duplicate n string = concat $ replicate n string

getTestCases :: Int -> IO [(String, String)]
getTestCases n = go n []
  where
    go 0 ret = return ret
    go n ret = do
      line <- getLine
      line2 <- getLine
      let tcase = (line, line2)
      -- print tcase
      -- print n
      go (n-1) (ret ++ [tcase])

-- isDiv :: String -> String -> Bool
-- isDiv a "" = True
-- isDiv "" a = True
-- isDiv a b =
--   let
--     lenA = length a
--     lenB = length b
--     sl = if lenA <= lenB then lenA else lenB
--     ll = lenA + lenB - sl
--     rmd = ll `rem` sl
--   in
--     if rmd == 0 then True else False

solve :: (String, String) -> String
solve ("",s) = s
solve (s,"") = s
solve (sa, sb) =
  let
    -- possbl = take (2 * sl) (duplicate 2 bgl) == duplicate 2 sgl
    -- fc = head sa
    -- fcb = head sb
    -- (possbl, ans) =
    --   if fc == fcb && all (==fc) sa && all (==fc) sb
    --   then (True, duplicate (lcm lsa lsb) [fc])
    --   else (False, "-1")
    -- (possbl2, ans2) =
    --   if (take (2 * sl) (duplicate 2 bgl) == duplicate 2 sgl) then (True, duplicate (lcmab `div` bl) bgl) else (False, "-1")
    -- already = if (bl `rem` sl == 0)
    --           then if (duplicate (bl `div` sl) sgl) == bgl
    --                then True
    --                else False
    --           else False
    opta = duplicate (lcmab `div` lsa) sa
    optb = duplicate (lcmab `div` lsb) sb
    possibl3 = if opta == optb then opta else "-1"
    lcmab = lcm lsa lsb
    lsa = length sa
    lsb = length sb
    -- (bl, bgl) = if (lsa >= lsb) then (lsa, sa) else (lsb, sb)
    -- (sl, sgl) = if (bgl == sa) then (lsb, sb) else (lsa, sa)
    -- nrp = lcmab `div` (length bgl)
    -- ans = duplicate bgl nrp

  in
    possibl3
    -- if already || possbl || possbl2
    -- then if already
    --       then bgl
    --       else if possbl
    --       then ans
    --       else ans2
    -- else "-1"

main :: IO ()
main = do
  ts <- getLine
  let t = read ts :: Int
  testCases <- getTestCases t
  traverse_ (putStrLn . solve) testCases

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

--
-- UTILITIES
--
import qualified Data.ByteString.Char8 as C8
import           Data.Maybe            (fromJust)

getInt :: IO Int
getInt = read <$> getLine

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

getInteger :: IO Integer
getInteger = read <$> getLine

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

--
-- MAIN
--

main :: IO ()
main = do
    q <- getInt
    replicateM_ q $ do
        s <- getLine
        t <- getLine
        let fs = factors s
        let ft = factors t
        let commonFactors = [(ds, dt, fs') | (ds, fs') <- fs, (dt, ft') <- ft, fs' == ft']
        putStrLn $ ans commonFactors

ans :: [(Int, Int, String)] -> String
ans [] = "-1"
ans cf = concat $ replicate (lcm ds dt) fs
  where
    (ds, dt, fs) = L.maximumBy (comparing (\(_, _, a) -> a)) cf

factors :: String -> [(Int, String)]
factors str = do
    let l = length str
    s <- tail $ L.inits str
    let (d, m) = l `divMod` length s
    guard (m == 0)
    guard (concat (replicate d s) == str)
    pure (d, s)

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

readInts = fmap (map read.words) getLine :: IO [Integer]
printArray [] = ""
printArray (x:xs) = show(x) ++" " ++ printArray xs

divisible a t n
    | a == "" = True
    | take n a == t = divisible (drop n a) t n
    | otherwise = False

printS = do
    ss<-getLine
    tt<-getLine
    let s = if (length ss > length tt) then ss else tt
        t = if (length ss > length tt) then tt else ss
        l = (div (lcm (length s) (length t)) (length s))
        a = concat $ replicate l s
    putStrLn $ if (divisible a t (length t)) then a else "-1"

main = do
    t<-readLn
    replicateM_ t printS

import Control.Monad

solve xs n = head [s|i<-[1..20],
                   mod n i == 0,
                   let d = div n i,
                   let s = take i xs,
                   let ts = concat $ replicate d s,
                   ts == xs]

printResult = do
    s <- getLine
    t <- getLine
    let
        n = length s
        m = length t
        s1 = solve s n
        t1 = solve t m
        n1 = div n $ length s1
        m1 = div m $ length t1
        r = if s1 == t1 then concat $ replicate (lcm m1 n1) s1 else show (-1)
    putStrLn r

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

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

readArray :: Read a => IO [a]
readArray = fmap (map read . words) getLine

readInts :: IO [Integer]
readInts = readArray

readInt :: IO Integer
readInt = readLn

startsWith :: String -> String -> Bool
startsWith s t = length s <= length t && s == take (length s) t

divides :: String -> String -> Bool
divides s [] = True
divides s t = startsWith s t && divides s (drop (length s) t)

solve :: String -> String -> Maybe String
solve s t =
    let u = concat $ replicate ((lcm (length s) (length t)) `div` (length s)) s in
    if divides s u && divides t u then Just u else Nothing

ans :: Maybe String -> String
ans = maybe "-1" id

solveCase :: IO String
solveCase = do
    s <- getLine
    t <- getLine
    pure $ ans $ solve s t

main :: IO ()
main = readLn >>= flip replicateM_ (solveCase >>= putStrLn)

{-# 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 :: String -> String -> Maybe String
solve s t = if sLcmString == tLcmString then Just sLcmString else Nothing
    where
        sLength = length s
        tLength = length t
        gcdLength = gcd sLength tLength
        sLcmString = join . replicate (tLength `div` gcdLength) $ s
        tLcmString = join . replicate (sLength `div` gcdLength) $ t

main :: IO ()
main = do
    t <- B8.getLine <&> readIntB8
    replicateM_ t $ do
        [s, t] <- replicateM 2 $ B8.getLine <&> head . B8.words <&> B8.unpack
        let answer = solve s t
        putStrLn $ fromMaybe "-1" answer

readString :: () -> (IO[Char])
readString () = do
    c <- getChar

    if (c==' ' || c=='\n')
        then return [c]
    else
        do
            rest <- readString()
            return ([c]++rest)

readInt :: () -> IO Int
readInt () = do
    help <- readString()
    let x = read help :: Int

    return x

printer :: () -> IO()
printer () = do
    putStr "1\n"
    printer()

isSignleCharacter :: (String) -> (Bool)
isSignleCharacter (s) = ((replicate (length s) (s!!0))==s)

cpyString :: (Int, String) -> (String)
cpyString (0, s) = ""
cpyString (cnt, s) = s++cpyString(cnt-1, s)

isDivisible :: (String, String) -> (Bool)
isDivisible (pattern, txt) = (cpyString((length txt) `div` length (pattern), pattern)==txt)

solveTestcase :: (Int) -> IO()
solveTestcase 0 = return ()
solveTestcase (testId) = do
    s <- getLine
    t <- getLine

    let solutions1 = [cpyString(cnt, s) | cnt <- [1..20], isDivisible(t, cpyString(cnt, s))]
    let solutions2 = [cpyString(cnt, t) | cnt <- [1..20], isDivisible(s, cpyString(cnt, t))]

    print ((solutions1++solutions2++["-1"])!!0)
    solveTestcase(testId-1)

main = do
    t <- readInt()
    solveTestcase(t)

readString :: () -> (IO[Char])
readString () = do
    c <- getChar

    if (c==' ' || c=='\n')
        then return [c]
    else
        do
            rest <- readString()
            return ([c]++rest)

readInt :: () -> IO Int
readInt () = do
    help <- readString()
    let x = read help :: Int

    return x

printer :: () -> IO()
printer () = do
    putStr "1\n"
    printer()

isSignleCharacter :: (String) -> (Bool)
isSignleCharacter (s) = ((replicate (length s) (s!!0))==s)

cpyString :: (Int, String) -> (String)
cpyString (0, s) = ""
cpyString (cnt, s) = s++cpyString(cnt-1, s)

solveTestcase :: (Int) -> IO()
solveTestcase 0 = return ()
solveTestcase (testId) = do
    s <- getLine
    t <- getLine

    if(s==(cpyString((length s) `div` (length t), t)))
        then do
            putStrLn s
            solveTestcase(testId-1)
    else if(t==(cpyString((length t) `div` (length s), s)))
        then do
            putStrLn t
            solveTestcase(testId-1)
    else if(isSignleCharacter(s)==True && isSignleCharacter(t)==True && (s!!0)==(t!!0))
        then do
            putStrLn (replicate (lcm (length s) (length t)) (s!!0))
            solveTestcase(testId-1)
    else do
        putStrLn "-1"
        solveTestcase(testId-1)

    --solveTestcase(testId-1)

main = do
    t <- readInt()
    solveTestcase(t)

readString :: () -> (IO[Char])
readString () = do
    c <- getChar

    if (c==' ' || c=='\n')
        then return [c]
    else
        do
            rest <- readString()
            return ([c]++rest)

readInt :: () -> IO Int
readInt () = do
    help <- readString()
    let x = read help :: Int

    return x

printer :: () -> IO()
printer () = do
    putStr "1\n"
    printer()

isSignleCharacter :: (String) -> (Bool)
isSignleCharacter (s) = ((replicate (length s) (s!!0))==s)

cpyString :: (Int, String) -> (String)
cpyString (0, s) = ""
cpyString (cnt, s) = s++cpyString(cnt-1, s)

solveTestcase :: (Int) -> IO()
solveTestcase 0 = return ()
solveTestcase (testId) = do
    s <- getLine
    t <- getLine

    if(s==(cpyString((length s) `div` (length t), t)))
        then do
            putStrLn s
            solveTestcase(testId-1)
    else if(t==(cpyString((length t) `div` (length s), s)))
        then do
            putStrLn t
            solveTestcase(testId-1)
    else if(isSignleCharacter(s)==True && isSignleCharacter(t)==True)
        then do
            putStrLn (replicate (lcm (length s) (length t)) (s!!0))
            solveTestcase(testId-1)
    else do
        putStrLn "-1"
        solveTestcase(testId-1)

    --solveTestcase(testId-1)

main = do
    t <- readInt()
    solveTestcase(t)

readString :: () -> (IO[Char])
readString () = do
    c <- getChar

    if (c==' ' || c=='\n')
        then return [c]
    else
        do
            rest <- readString()
            return ([c]++rest)

readInt :: () -> IO Int
readInt () = do
    help <- readString()
    let x = read help :: Int

    return x

printer :: () -> IO()
printer () = do
    putStr "1\n"
    printer()

isSignleCharacter :: (String) -> (Bool)
isSignleCharacter (s) = ((replicate (length s) (s!!0))==s)

cpyString :: (Int, String) -> (String)
cpyString (0, s) = ""
cpyString (cnt, s) = s++cpyString(cnt-1, s)

solveTestcase :: (Int) -> IO()
solveTestcase 0 = return ()
solveTestcase (testId) = do
    s <- getLine
    t <- getLine

    if(s==(cpyString((length s) `div` (length t), t)))
        then do
            putStr s
            solveTestcase(testId-1)
    else if(t==(cpyString((length t) `div` (length s), s)))
        then do
            putStr t
            solveTestcase(testId-1)
    else if(isSignleCharacter(s)==True && isSignleCharacter(t)==True)
        then do
            putStr (replicate (lcm (length s) (length t)) (s!!0))
            solveTestcase(testId-1)
    else do
        putStr "-1"
        solveTestcase(testId-1)

    --solveTestcase(testId-1)

main = do
    t <- readInt()
    solveTestcase(t)

readString :: () -> (IO[Char])
readString () = do
    c <- getChar

    if (c==' ' || c=='\n')
        then return [c]
    else
        do
            rest <- readString()
            return ([c]++rest)

readInt :: () -> IO Int
readInt () = do
    help <- readString()
    let x = read help :: Int

    return x

printer :: () -> IO()
printer () = do
    putStr "1\n"
    printer()

isSignleCharacter :: (String) -> (Bool)
isSignleCharacter (s) = ((replicate (length s) (s!!0))==s)

cpyString :: (Int, String) -> (String)
cpyString (0, s) = ""
cpyString (cnt, s) = s++cpyString(cnt-1, s)

solveTestcase :: (Int) -> IO()
solveTestcase 0 = return ()
solveTestcase (testId) = do
    s <- getLine
    t <- getLine

    if(s==(cpyString((length s) `div` (length t), t)))
        then do
            print s
            solveTestcase(testId-1)
    else if(t==(cpyString((length t) `div` (length s), s)))
        then do
            print t
            solveTestcase(testId-1)
    else if(isSignleCharacter(s)==True && isSignleCharacter(t)==True)
        then do
            print (replicate (lcm (length s) (length t)) (s!!0))
            solveTestcase(testId-1)
    else do
        print "-1"
        solveTestcase(testId-1)

    --solveTestcase(testId-1)

main = do
    t <- readInt()
    solveTestcase(t)

module Main where
import Data.Foldable (traverse_)
import Data.List (sort)

duplicate :: Int ->  String -> String
duplicate n string = concat $ replicate n string

getTestCases :: Int -> IO [(String, String)]
getTestCases n = go n []
  where
    go 0 ret = return ret
    go n ret = do
      line <- getLine
      line2 <- getLine
      let tcase = (line, line2)
      -- print tcase
      -- print n
      go (n-1) (ret ++ [tcase])

-- isDiv :: String -> String -> Bool
-- isDiv a "" = True
-- isDiv "" a = True
-- isDiv a b =
--   let
--     lenA = length a
--     lenB = length b
--     sl = if lenA <= lenB then lenA else lenB
--     ll = lenA + lenB - sl
--     rmd = ll `rem` sl
--   in
--     if rmd == 0 then True else False

solve :: (String, String) -> String
solve ("",s) = s
solve (s,"") = s
solve (sa, sb) =
  let
    -- possbl = take (2 * sl) (duplicate 2 bgl) == duplicate 2 sgl
    fc = head sa
    fcb = head sb
    (possbl, ans) =
      if fc == fcb && all (==fc) sa && all (==fc) sb
      then (True, duplicate (lcm lsa lsb) [fc])
      else (False, "-1")
    (possbl2, ans2) =
      if (take (2 * sl) (duplicate 2 bgl) == duplicate 2 sgl) then (True, duplicate (lcmab `div` bl) bgl) else (False, "-1")
    already = if (bl `rem` sl == 0)
              then if (duplicate (bl `div` sl) sgl) == bgl
                   then True
                   else False
              else False
    lcmab = lcm lsa lsb
    lsa = length sa
    lsb = length sb
    (bl, bgl) = if (lsa >= lsb) then (lsa, sa) else (lsb, sb)
    (sl, sgl) = if (bgl == sa) then (lsb, sb) else (lsa, sa)
    -- nrp = lcmab `div` (length bgl)
    -- ans = duplicate bgl nrp

  in
    if already || possbl || possbl2
    then if already
          then bgl
          else if possbl
          then ans
          else ans2
    else "-1"

main :: IO ()
main = do
  ts <- getLine
  let t = read ts :: Int
  testCases <- getTestCases t
  traverse_ (putStrLn . solve) testCases

module Main where
import Data.Foldable (traverse_)
import Data.List (sort)

duplicate :: Int ->  String -> String
duplicate n string = concat $ replicate n string

getTestCases :: Int -> IO [(String, String)]
getTestCases n = go n []
  where
    go 0 ret = return ret
    go n ret = do
      line <- getLine
      line2 <- getLine
      let tcase = (line, line2)
      -- print tcase
      -- print n
      go (n-1) (ret ++ [tcase])

-- isDiv :: String -> String -> Bool
-- isDiv a "" = True
-- isDiv "" a = True
-- isDiv a b =
--   let
--     lenA = length a
--     lenB = length b
--     sl = if lenA <= lenB then lenA else lenB
--     ll = lenA + lenB - sl
--     rmd = ll `rem` sl
--   in
--     if rmd == 0 then True else False

solve :: (String, String) -> String
solve ("",s) = s
solve (s,"") = s
solve (sa, sb) =
  let
    -- possbl = take (2 * sl) (duplicate 2 bgl) == duplicate 2 sgl
    fc = head sa
    fcb = head sb
    (possbl, ans) =
      if fc == fcb && all (==fc) sa && all (==fc) sb
      then (True, duplicate (lcm lsa lsb) [fc])
      else (False, "-1")
    (possbl2, ans2) =
      if (take (2 * sl) (duplicate 2 bgl) == duplicate 2 sgl) then (True, duplicate 2 bgl) else (False, "-1")
    already = if (bl `rem` sl == 0)
              then if (duplicate (bl `div` sl) sgl) == bgl
                   then True
                   else False
              else False
    lcmab = lcm lsa lsb
    lsa = length sa
    lsb = length sb
    (bl, bgl) = if (lsa >= lsb) then (lsa, sa) else (lsb, sb)
    (sl, sgl) = if (bgl == sa) then (lsb, sb) else (lsa, sa)
    -- nrp = lcmab `div` (length bgl)
    -- ans = duplicate bgl nrp

  in
    if already || possbl || possbl2
    then if already
          then bgl
          else if possbl
          then ans
          else ans2
    else "-1"

main :: IO ()
main = do
  ts <- getLine
  let t = read ts :: Int
  testCases <- getTestCases t
  traverse_ (putStrLn . solve) testCases

module Main where
import Data.Foldable (traverse_)
import Data.List (sort)

duplicate :: Int ->  String -> String
duplicate n string = concat $ replicate n string

getTestCases :: Int -> IO [(String, String)]
getTestCases n = go n []
  where
    go 0 ret = return ret
    go n ret = do
      line <- getLine
      line2 <- getLine
      let tcase = (line, line2)
      -- print tcase
      -- print n
      go (n-1) (ret ++ [tcase])

-- isDiv :: String -> String -> Bool
-- isDiv a "" = True
-- isDiv "" a = True
-- isDiv a b =
--   let
--     lenA = length a
--     lenB = length b
--     sl = if lenA <= lenB then lenA else lenB
--     ll = lenA + lenB - sl
--     rmd = ll `rem` sl
--   in
--     if rmd == 0 then True else False

solve :: (String, String) -> String
solve ("",s) = s
solve (s,"") = s
solve (sa, sb) =
  let
    -- possbl = take (2 * sl) (duplicate 2 bgl) == duplicate 2 sgl
    fc = head sa
    fcb = head sb
    (possbl, ans) =
      if fc == fcb && all (==fc) sa && all (==fc) sb
      then (True, duplicate (lcm lsa lsb) [fc])
      else (False, "-1")
    (possbl2, ans2) =
      if (take (2 * sl) (duplicate 2 bgl) == duplicate 2 sgl) then (True, duplicate 2 bgl) else (False, "-1")
    already = if (bl `rem` sl == 0)
              then if (duplicate (bl `div` sl) sgl) == bgl
                   then True
                   else False
              else False
    lcmab = lcm lsa lsb
    lsa = length sa
    lsb = length sb
    (bl, bgl) = if (lsa >= lsb) then (lsa, sa) else (lsb, sb)
    (sl, sgl) = if (bgl == sa) then (lsb, sb) else (lsa, sa)
    -- nrp = lcmab `div` (length bgl)
    -- ans = duplicate bgl nrp

  in
    if already || possbl || possbl2
    then if already
          then bgl
          else if possbl2
          then ans2
          else ans
    else "-1"

main :: IO ()
main = do
  ts <- getLine
  let t = read ts :: Int
  testCases <- getTestCases t
  traverse_ (putStrLn . solve) testCases

module Main where
import Data.Foldable (traverse_)
import Data.List (sort)

duplicate :: Int ->  String -> String
duplicate n string = concat $ replicate n string

getTestCases :: Int -> IO [(String, String)]
getTestCases n = go n []
  where
    go 0 ret = return ret
    go n ret = do
      line <- getLine
      line2 <- getLine
      let tcase = (line, line2)
      -- print tcase
      -- print n
      go (n-1) (ret ++ [tcase])

-- isDiv :: String -> String -> Bool
-- isDiv a "" = True
-- isDiv "" a = True
-- isDiv a b =
--   let
--     lenA = length a
--     lenB = length b
--     sl = if lenA <= lenB then lenA else lenB
--     ll = lenA + lenB - sl
--     rmd = ll `rem` sl
--   in
--     if rmd == 0 then True else False

solve :: (String, String) -> String
solve ("",s) = s
solve (s,"") = s
solve (sa, sb) =
  let
    -- possbl = take (2 * sl) (duplicate 2 bgl) == duplicate 2 sgl
    fc = head sa
    fcb = head sb
    (possbl, ans) =
      if fc == fcb && all (==fc) sa && all (==fc) sb
      then (True, duplicate (lcm lsa lsb) [fc])
      else (False, "-1")
    already = if (bl `rem` sl == 0)
              then if (duplicate (bl `div` sl) sgl) == bgl
                   then True
                   else False
              else False
    lcmab = lcm lsa lsb
    lsa = length sa
    lsb = length sb
    (bl, bgl) = if (lsa >= lsb) then (lsa, sa) else (lsb, sb)
    (sl, sgl) = if (bgl == sa) then (lsb, sb) else (lsa, sa)
    -- nrp = lcmab `div` (length bgl)
    -- ans = duplicate bgl nrp

  in
    if already || possbl
    then if already
          then bgl
          else ans
    else "-1"

main :: IO ()
main = do
  ts <- getLine
  let t = read ts :: Int
  testCases <- getTestCases t
  traverse_ (putStrLn . solve) testCases

module Main where
import Data.Foldable (traverse_)
import Data.List (sort)

duplicate :: Int ->  String -> String
duplicate n string = concat $ replicate n string

getTestCases :: Int -> IO [(String, String)]
getTestCases n = go n []
  where
    go 0 ret = return ret
    go n ret = do
      line <- getLine
      line2 <- getLine
      let tcase = (line, line2)
      -- print tcase
      -- print n
      go (n-1) (ret ++ [tcase])

isDiv :: String -> String -> Bool
isDiv a "" = True
isDiv "" a = True
isDiv a b =
  let
    lenA = length a
    lenB = length b
    sl = if lenA <= lenB then lenA else lenB
    ll = lenA + lenB - sl
    rmd = ll `rem` sl
  in
    if rmd == 0 then True else False

solve :: (String, String) -> String
solve ("",s) = s
solve (s,"") = s
solve (sa, sb) =
  let
    possbl = take (2 * sl) (duplicate 2 bgl) == duplicate 2 sgl
    already = if (bl `rem` sl == 0)
              then if (duplicate (bl `div` sl) sgl) == bgl
                   then True
                   else False
              else False
    lcmab = lcm lsa lsb
    lsa = length sa
    lsb = length sb
    (bl, bgl) = if (lsa >= lsb) then (lsa, sa) else (lsb, sb)
    (sl, sgl) = if (bgl == sa) then (lsb, sb) else (lsa, sa)
    -- nrp = lcmab `div` (length bgl)
    -- ans = duplicate bgl nrp

  in
    if already || possbl
    then if already
          then bgl
          else (duplicate 2 bgl) else "-1"

main :: IO ()
main = do
  ts <- getLine
  let t = read ts :: Int
  testCases <- getTestCases t
  traverse_ (putStrLn . solve) testCases

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

--
-- UTILITIES
--
import qualified Data.ByteString.Char8 as C8
import           Data.Maybe            (fromJust)

getInt :: IO Int
getInt = read <$> getLine

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

getInteger :: IO Integer
getInteger = read <$> getLine

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

--
-- MAIN
--

main :: IO ()
main = do
    q <- getInt
    replicateM_ q $ do
        s@(s1:_) <- getLine
        t <- getLine
        let ls = length s
        let lt = length t
        let result | all (==s1) s && all (==s1) t = Just (replicate (lcm ls lt) s1)
                   | ls < lt && t `consistsOf` s = Just t
                   | lt < ls && s `consistsOf` t = Just s
                   | otherwise = Nothing
        case result of
          Just s -> putStrLn s
          _ -> putStrLn "-1"

consistsOf :: String -> String -> Bool
consistsOf "" _ = True
consistsOf s ref = ref `L.isPrefixOf` s && drop (length ref) s `consistsOf` ref


You are given an integer $$$k$$$ and a string $$$s$$$ that consists only of characters 'a' (a lowercase Latin letter) and '*' (an asterisk).Each asterisk should be replaced with several (from $$$0$$$ to $$$k$$$ inclusive) lowercase Latin letters 'b'. Different asterisk can be replaced with different counts of letter 'b'.The result of the replacement is called a BA-string.Two strings $$$a$$$ and $$$b$$$ are different if they either have different lengths or there exists such a position $$$i$$$ that $$$a_i \neq b_i$$$.A string $$$a$$$ is lexicographically smaller than a string $$$b$$$ if and only if one of the following holds:   $$$a$$$ is a prefix of $$$b$$$, but $$$a \ne b$$$;  in the first position where $$$a$$$ and $$$b$$$ differ, the string $$$a$$$ has a letter that appears earlier in the alphabet than the corresponding letter in $$$b$$$. Now consider all different BA-strings and find the $$$x$$$-th lexicographically smallest of them.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 2000$$$) — the number of testcases. The first line of each testcase contains three integers $$$n$$$, $$$k$$$ and $$$x$$$ ($$$1 \le n \le 2000$$$; $$$0 \le k \le 2000$$$; $$$1 \le x \le 10^{18}$$$). $$$n$$$ is the length of string $$$s$$$. The second line of each testcase is a string $$$s$$$. It consists of $$$n$$$ characters, each of them is either 'a' (a lowercase Latin letter) or '*' (an asterisk). The sum of $$$n$$$ over all testcases doesn't exceed $$$2000$$$. For each testcase $$$x$$$ doesn't exceed the total number of different BA-strings. String $$$s$$$ contains at least one character 'a'.

For each testcase, print a single string, consisting only of characters 'b' and 'a' (lowercase Latin letters) — the $$$x$$$-th lexicographically smallest BA-string.

NoteIn the first testcase of the example, BA-strings ordered lexicographically are:   a  ab  abb  abbb  abbbb In the second testcase of the example, BA-strings ordered lexicographically are:   aa  aba  abba Note that string "aba" is only counted once, even though there are two ways to replace asterisks with characters 'b' to get it.

{-# LANGUAGE TypeApplications #-}
module Main where
import           Control.Monad                  ( replicateM_ )
import           Data.List                      ( genericReplicate
                                                , scanl'
                                                )

-- infinite list of prime numbers
primes :: [Integer]
primes = 2 : filter isPrime [3, 5 ..]
  where
    isPrime n = not (any (divides n) (takeWhile (\p -> p * p <= n) primes))
    divides n p = n `mod` p == 0

-- calculateBase :: Int -> [Int] -> [(Int, Int)]
calculateBase k xs = scanr (\x (q, y) -> (x * k, (q + 1) * y)) (last xs * k, 1) (take (length xs - 1) xs)

-- >>> calculateBase 3 [2,3]
-- [(2,10),(9,1)]

-- convertToBase :: Int -> Int -> [(Int, Int)] -> [Int]
convertToBase k a = fmap snd . tail . scanl' (\(rest, _) (q, x) -> let len = min q (rest `div` x) in (rest - len * x, len)) (a, 0)

-- >>> convertToBase 3 19 (calculateBase 3 [2,3])
-- [1,9]

-- | @replaceBase bases k n str@ replaces each segment of asterisks in @str@ with the corresponding digit of 'b' as @n@.
-- replaceBase :: [(Int, Int)] -> Int -> Int -> String -> String
replaceBase bases k n = phi [] (convertToBase k n bases)
  where
    phi acc digits           []         = concat acc
    phi acc (digit : digits) ('*' : xs) = phi (acc ++ [genericReplicate digit 'b']) digits xs
    phi acc digits           (x   : xs) = phi (acc ++ [[x]]) digits xs

main :: IO ()
main = do
    t <- readLn
    replicateM_ t $ do
        [_, k, x]       <- fmap (map (read @Integer) . words) getLine
        (str, segments) <- readStr
        putStrLn $ replaceBase (calculateBase k segments) k (x - 1) str
  where
    readStr = go "" [] 0 <$> getLine
    go acc segments current [] =
        ( case reverse acc of
            acc'@('*' : _) -> acc'
            acc'           -> '*' : acc'
        , reverse (current : segments)
        )
    go acc segments current (x : xs)
        | x == '*' = case acc of
            ('*' : _) -> go acc segments (current + 1) xs
            _         -> go ('*' : acc) segments 1 xs
        | otherwise = go (x : acc) (if current > 0 || null acc then current : segments else segments) 0 xs

import Control.Monad (replicateM)

main :: IO ()
main = do
    t <- read <$> getLine
    res <- replicateM t $ do
        [n, k, x] <- map read . words <$> getLine :: IO [Integer]
        solve n k x <$> getLine
    putStrLn . unlines $ res

solve :: Integer -> Integer -> Integer -> String -> String
solve n k x s = ans
    where
        stars   = words [if c == '*' then c else ' ' | c <- s]
        as      = words [if c == 'a' then c else ' ' | c <- 'a':s]
        bases   = reverse $  map ((1 +) . (fromInteger k *) .  length) stars
        num     = reverse $ convert bases (x-1)
        _:ans   = blend as (map (`replicate` 'b') num)

convert :: [Int] -> Integer -> [Int]
convert [] _        = []
convert (b:bs) x    = fromInteger m : convert bs q
    where
        (q, m) = divMod x (toInteger b)

blend :: [String] -> [String] -> String
blend (x:xs) ys = x ++ blend ys xs
blend [] ys = concat ys

{-# LANGUAGE TypeApplications #-}
module Main where
import           Control.Monad                  ( replicateM_ )
import           Data.List                      ( scanl' )

-- infinite list of prime numbers
primes :: [Integer]
primes = 2 : filter isPrime [3, 5 ..]
  where
    isPrime n = not (any (divides n) (takeWhile (\p -> p * p <= n) primes))
    divides n p = n `mod` p == 0

calculateBase :: Int -> [Int] -> [(Int, Int)]
calculateBase k xs = scanr (\x (q, y) -> (x * k, (q + 1) * y)) (last xs * k, 1) (take (length xs - 1) xs)

-- >>> calculateBase 3 [2,3]
-- [(2,10),(9,1)]

convertToBase :: Int -> Int -> [(Int, Int)] -> [Int]
convertToBase k a = fmap snd . tail . scanl' (\(rest, _) (q, x) -> let len = min q (rest `div` x) in (rest - len * x, len)) (a, 0)

-- >>> convertToBase 3 19 (calculateBase 3 [2,3])
-- [1,9]

-- | @replaceBase bases k n str@ replaces each segment of asterisks in @str@ with the corresponding digit of 'b' as @n@.
replaceBase :: [(Int, Int)] -> Int -> Int -> String -> String
replaceBase bases k n = phi [] (convertToBase k n bases)
  where
    phi acc digits           []         = concat acc
    phi acc (digit : digits) ('*' : xs) = phi (acc ++ [replicate digit 'b']) digits xs
    phi acc digits           (x   : xs) = phi (acc ++ [[x]]) digits xs

main :: IO ()
main = do
    t <- readLn
    replicateM_ t $ do
        [_, k, x]       <- fmap (map (read @Int) . words) getLine
        (str, segments) <- readStr
        putStrLn $ replaceBase (calculateBase k segments) k (x - 1) str
  where
    readStr = go "" [] 0 <$> getLine
    go acc segments current [] =
        ( case reverse acc of
            acc'@('*' : _) -> acc'
            acc'           -> '*' : acc'
        , reverse (current : segments)
        )
    go acc segments current (x : xs)
        | x == '*' = case acc of
            ('*' : _) -> go acc segments (current + 1) xs
            _         -> go ('*' : acc) segments 1 xs
        | otherwise = go (x : acc) (if current > 0 || null acc then current : segments else segments) 0 xs

{-# LANGUAGE TypeApplications #-}
module Main where
import           Control.Monad                  ( replicateM_ )
import           Data.List                      ( scanl' )
import           Debug.Trace                    ( traceShow )

-- infinite list of prime numbers
primes :: [Integer]
primes = 2 : filter isPrime [3, 5 ..]
  where
    isPrime n = not (any (divides n) (takeWhile (\p -> p * p <= n) primes))
    divides n p = n `mod` p == 0

calculateBase :: Int -> [Int] -> [(Int, Int)]
calculateBase k xs = scanr (\x (q, y) -> (x, (q + 1) * y)) (last xs * k, 1) (take (length xs - 1) xs)

-- >>> calculateBase 3 [2,3]
-- [(2,10),(9,1)]

convertToBase :: Int -> Int -> [(Int, Int)] -> [Int]
convertToBase k a = fmap snd . tail . scanl' (\(rest, _) (q, x) -> let len = min (q * k) (rest `div` x) in (rest - len * x, len)) (a, 0)

-- >>> convertToBase 3 19 (calculateBase 3 [2,3])
-- [1,9]

-- | @replaceBase bases k n str@ replaces each segment of asterisks in @str@ with the corresponding digit of 'b' as @n@.
replaceBase :: [(Int, Int)] -> Int -> Int -> String -> String
replaceBase bases k n = phi [] (convertToBase k n bases)
  where
    phi acc digits           []         = concat acc
    phi acc (digit : digits) ('*' : xs) = phi (acc ++ [replicate digit 'b']) digits xs
    phi acc digits           (x   : xs) = phi (acc ++ [[x]]) digits xs

main :: IO ()
main = do
    t <- readLn
    replicateM_ t $ do
        [_, k, x]       <- fmap (map (read @Int) . words) getLine
        (str, segments) <- readStr
        putStrLn $ replaceBase (calculateBase k segments) k (x - 1) str
  where
    readStr = go "" [] 0 <$> getLine
    go acc segments current [] =
        ( case reverse acc of
            acc'@('*' : _) -> acc'
            acc'           -> '*' : acc'
        , reverse (current : segments)
        )
    go acc segments current (x : xs)
        | x == '*' = case acc of
            ('*' : _) -> go acc segments (current + 1) xs
            _         -> go ('*' : acc) segments 1 xs
        | otherwise = go (x : acc) (if current > 0 || null acc then current : segments else segments) 0 xs

{-# LANGUAGE TypeApplications #-}
module Main where
import           Control.Monad                  ( replicateM_ )
import           Data.List                      ( scanl' )
import           Debug.Trace                    ( traceShow )

-- infinite list of prime numbers
primes :: [Integer]
primes = 2 : filter isPrime [3, 5 ..]
  where
    isPrime n = not (any (divides n) (takeWhile (\p -> p * p <= n) primes))
    divides n p = n `mod` p == 0

calculateBase :: Int -> [Int] -> [(Int, Int)]
calculateBase k xs = scanr (\x (q, y) -> (x, (q + 1) * y)) (last xs * k, 1) (take (length xs - 1) xs)

-- >>> calculateBase 3 [2,3]
-- [(2,10),(9,1)]

convertToBase :: Int -> Int -> [(Int, Int)] -> [Int]
convertToBase k a = fmap snd . tail . scanl' (\(rest, _) (q, x) -> let len = min (q * k) (rest `div` x) in (rest - len * x, len)) (a, 0)

-- >>> convertToBase 3 19 (calculateBase 3 [2,3])
-- [1,9]

-- | @replaceBase bases k n str@ replaces each segment of asterisks in @str@ with the corresponding digit of 'b' as @n@.
replaceBase :: [(Int, Int)] -> Int -> Int -> String -> String
replaceBase bases k n = phi [] (convertToBase k n bases)
  where
    phi acc digits           []         = concat acc
    phi acc (digit : digits) ('*' : xs) = phi (acc ++ [replicate digit 'b']) digits xs
    phi acc digits           (x   : xs) = phi (acc ++ [[x]]) digits xs

main :: IO ()
main = do
    t <- readLn
    replicateM_ t $ do
        [_, k, x]       <- fmap (map (read @Int) . words) getLine
        (str, segments) <- readStr
        putStrLn $ replaceBase (calculateBase k segments) k (x - 1) str
  where
    readStr = go "" [] 0 <$> getLine
    go acc segments current [] =
        ( case reverse acc of
            acc'@('*' : _) -> acc'
            acc'           -> '*' : acc'
        , reverse (current : segments)
        )
    go acc segments current (x : xs)
        | x == '*' = case acc of
            ('*' : _) -> go acc segments (current + 1) xs
            _         -> go ('*' : acc) segments 1 xs
        | otherwise = go (x : acc) (current : segments) 0 xs

{-# LANGUAGE TypeApplications #-}
module Main where
import           Control.Monad                  ( replicateM_ )
import           Data.List                      ( scanl' )

-- infinite list of prime numbers
primes :: [Integer]
primes = 2 : filter isPrime [3, 5 ..]
  where
    isPrime n = not (any (divides n) (takeWhile (\p -> p * p <= n) primes))
    divides n p = n `mod` p == 0

calculateBase :: Int -> [Int] -> [(Int, Int)]
calculateBase k xs = scanr (\x (q, y) -> (x, (q + 1) * y)) (last xs * k, 1) (take (length xs - 1) xs)

-- >>> calculateBase 3 [2,3]
-- [(2,10),(9,1)]

convertToBase :: Int -> Int -> [(Int, Int)] -> [Int]
convertToBase k a = fmap snd . tail . scanl' (\(rest, _) (q, x) -> let len = min q (a `div` x) in (rest - len * x, len)) (a, 0)

-- >>> convertToBase 3 19 (calculateBase 3 [2,3])
-- [1,9]

-- | @replaceBase bases k n str@ replaces each segment of asterisks in @str@ with the corresponding digit of 'b' as @n@.
replaceBase :: [(Int, Int)] -> Int -> Int -> String -> String
replaceBase bases k n = phi [] (convertToBase k n bases)
  where
    phi acc digits           []         = concat acc
    phi acc (digit : digits) ('*' : xs) = phi (acc ++ [replicate digit 'b']) digits xs
    phi acc digits           (x   : xs) = phi (acc ++ [[x]]) digits xs

main :: IO ()
main = do
    t <- readLn
    replicateM_ t $ do
        [_, k, x]       <- fmap (map (read @Int) . words) getLine
        (str, segments) <- readStr
        putStrLn $ replaceBase (calculateBase k segments) k (x - 1) str
  where
    readStr = go "" [] 0 <$> getLine
    go acc segments current [] =
        ( case reverse acc of
            acc'@('*' : _) -> acc'
            acc'           -> '*' : acc'
        , reverse (current : segments)
        )
    go acc segments current (x : xs)
        | x == '*' = case acc of
            ('*' : _) -> go acc segments (current + 1) xs
            _         -> go ('*' : acc) segments 1 xs
        | otherwise = go (x : acc) (current : segments) 0 xs