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 [] []

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

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


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 + 1 - s) / fromIntegral d
solve m _ = m

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


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

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) -> 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


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
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 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))]

    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

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


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


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

import Data.List
import Data.Int
import Data.Bits
import Data.Maybe
import Data.Array.Unboxed
import Data.Array.ST
import Data.Array.Base
import qualified Data.ByteString.Char8 as B

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

instance Functor (State s) where
    fmap f m = State $ runState m >>> first f

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

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

get :: State s s
get = State $ id &&& id
put :: s -> State s ()
put = State . const . ((),)
modify :: (s -> s) -> State s ()
modify = State . (.) ((,) ())
evalState :: State s a -> s -> a
evalState = (.) fst . runState
execState :: State s a -> s -> s
execState = (.) snd . runState

readInt = fromJust . fmap fst . B.readInt
readInts = map readInt . B.words <$> B.getLine
readIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine
readLns :: Read a => IO [a]
readLns = map read . words <$> getLine
cmpFst (a,_) (b,_) = compare a b
cmpSnd (_,a) (_,b) = compare a b
cmpLen a b = length a `compare` length b
swap (a,b) = (b,a)
l2p (a:b:_) = (a,b)
p2l (a,b) = [a,b]
itof :: Int -> Double
itof = fromIntegral
defaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e
defaultArray = accumArray $ curry snd
flatten :: [(a,[(b,c)])] -> [((a,b),c)]
flatten = (=<<) $ uncurry $ fmap . first . (,)
stepM_ :: Monad m => a -> (a -> Bool) -> (a -> a) -> (a -> m ()) -> m ()
stepM_ i judge incr step = sub i where
    sub i | judge i = step i >> sub (incr i) | otherwise = return ()
thru :: Monad m => (v -> m ()) -> v -> m v
thru m v = m v >> return v
inf = maxBound `div` 2 :: Int

main = do
    sn:l <- B.lines <$> B.getContents
    let n = readInt sn
    let (_es,sq:l') = splitAt (n-1) l
    let es = map (map readInt . B.words) _es
    let q = readInt sq
    let qs = map (map readInt . B.words) l'
    putStr $ unlines $ map (printf "%.6f") $ solve n es q qs

solve :: Int -> [[Int]] -> Int -> [[Int]] -> [Double]
solve n es q qs = runST doit where
    n' :: Integer
    n' = fromIntegral n
    edges = buildTree n es
    ws = [ fromIntegral w | [_,_,w] <- es ]
    doit :: ST s [Double]
    doit = do
        edgeLength <- newListArray (0,n-2) ws :: ST s (STUArray s Int Int64)
        let cost0 = sum $ zipWith (*) ws (elems edges)
        go cost0 edgeLength qs
    go :: Int64 -> (STUArray s Int Int64) -> [[Int]] -> ST s [Double]
    go _ _ [] = return []
    go !cost edgeLength ([ri,wi]:qs) = do
        wi' <- unsafeRead edgeLength (ri-1)
        let e = 3 * fromIntegral cost' / fromIntegral (n' * (n'-1) `div` 2)
            r = unsafeAt edges (ri-1)
            cost' = cost + fromIntegral (fromIntegral wi - wi') * r
        unsafeWrite edgeLength (ri-1) (fromIntegral wi)
        (e:) <$> go cost' edgeLength qs

buildTree :: Int -> [[Int]] -> UArray Int Int64
buildTree n es = doit where
    g :: Array Int [(Int,Int)]
    g = accumArray (flip (:)) [] (1,n) $ do
        (i,[a,b,w]) <- zip [1..] es
        [(a,(b,i)),(b,(a,i))]
    n' = fromIntegral n
    doit = runSTUArray $ do
        a <- newArray_ (0,n-2)
        let dfs pv v = do
            let us = [ (u,i-1) | (u,i) <- g ! v, u /= pv ]
            fmap ((+1).sum) $ forM us $ \(u,i) -> do
                ci <- dfs v u
                unsafeWrite a i (ci * (n'- ci))
                return ci
        dfs (-1) 1
        return a

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

import Data.List
import Data.Int
import Data.Bits
import Data.Maybe
import Data.Array.Unboxed
import Data.Array.ST
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.ByteString.Char8 as B
import qualified Data.IntMap as IM

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

instance Functor (State s) where
    fmap f m = State $ runState m >>> first f

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

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

get :: State s s
get = State $ id &&& id
put :: s -> State s ()
put = State . const . ((),)
modify :: (s -> s) -> State s ()
modify = State . (.) ((,) ())
evalState :: State s a -> s -> a
evalState = (.) fst . runState
execState :: State s a -> s -> s
execState = (.) snd . runState

readInt = fromJust . fmap fst . B.readInt
readInts = map readInt . B.words <$> B.getLine
readIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine
readLns :: Read a => IO [a]
readLns = map read . words <$> getLine
cmpFst (a,_) (b,_) = compare a b
cmpSnd (_,a) (_,b) = compare a b
cmpLen a b = length a `compare` length b
swap (a,b) = (b,a)
l2p (a:b:_) = (a,b)
p2l (a,b) = [a,b]
itof :: Int -> Double
itof = fromIntegral
defaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e
defaultArray = accumArray $ curry snd
flatten :: [(a,[(b,c)])] -> [((a,b),c)]
flatten = (=<<) $ uncurry $ fmap . first . (,)
stepM_ :: Monad m => a -> (a -> Bool) -> (a -> a) -> (a -> m ()) -> m ()
stepM_ i judge incr step = sub i where
    sub i | judge i = step i >> sub (incr i) | otherwise = return ()
thru :: Monad m => (v -> m ()) -> v -> m v
thru m v = m v >> return v
inf = maxBound `div` 2 :: Int

main = do
    sn:l <- B.lines <$> B.getContents
    let n = readInt sn
    let (_es,sq:l') = splitAt (n-1) l
    let es = map (map readInt . B.words) _es
    let q = readInt sq
    let qs = map (map readInt . B.words) l'
    putStr $ unlines $ map (printf "%.6f") $ solve n es q qs

solve :: Int -> [[Int]] -> Int -> [[Int]] -> [Double]
solve n es q qs = runST doit where
    n' :: Integer
    n' = fromIntegral n
    doit = do
        edges <- buildTree n es
        cost0 <- do
            es <- getElems edges
            return $ sum $ [ fromIntegral w * l * (n'-l) | (w,l) <- es ]
        go cost0 edges qs
    go _ _ [] = return []
    go !cost edges ([ri,wi]:qs) = do
        (wi',l) <- readArray edges ri
        let e = 3 * fromIntegral cost' / fromIntegral (n' * (n'-1) `div` 2)
            cost' = cost + fromIntegral (wi - wi') * l * (n'-l)
        writeArray edges ri (wi,l)
        (e:) <$> go cost' edges qs

buildTree :: Int -> [[Int]] -> ST s (STArray s Int (Int,Integer))
buildTree n es = doit where
    g :: Array Int [(Int,Int,Int)]
    g = accumArray (flip (:)) [] (1,n) $ do
        (i,[a,b,w]) <- zip [1..] es
        [(a,(b,w,i)),(b,(a,w,i))]
    doit = do
        a <- newArray_ (1,n-1)
        let dfs pv v = do
            let us = [ (u,w,i) | (u,w,i) <- g ! v, u /= pv]
            fmap ((+1).sum) $ forM us $ \(u,w,i) -> do
                ci <- dfs v u
                writeArray a i (w,ci)
                return ci
        dfs (-1) 1
        return a

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

import Data.List
import Data.Int
import Data.Bits
import Data.Maybe
import Data.Array.Unboxed
import Data.Array.ST
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.ByteString.Char8 as B
import qualified Data.IntMap as IM

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

instance Functor (State s) where
    fmap f m = State $ runState m >>> first f

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

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

get :: State s s
get = State $ id &&& id
put :: s -> State s ()
put = State . const . ((),)
modify :: (s -> s) -> State s ()
modify = State . (.) ((,) ())
evalState :: State s a -> s -> a
evalState = (.) fst . runState
execState :: State s a -> s -> s
execState = (.) snd . runState

readInt = fromJust . fmap fst . B.readInt
readInts = map readInt . B.words <$> B.getLine
readIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine
readLns :: Read a => IO [a]
readLns = map read . words <$> getLine
cmpFst (a,_) (b,_) = compare a b
cmpSnd (_,a) (_,b) = compare a b
cmpLen a b = length a `compare` length b
swap (a,b) = (b,a)
l2p (a:b:_) = (a,b)
p2l (a,b) = [a,b]
itof :: Int -> Double
itof = fromIntegral
defaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e
defaultArray = accumArray $ curry snd
flatten :: [(a,[(b,c)])] -> [((a,b),c)]
flatten = (=<<) $ uncurry $ fmap . first . (,)
stepM_ :: Monad m => a -> (a -> Bool) -> (a -> a) -> (a -> m ()) -> m ()
stepM_ i judge incr step = sub i where
    sub i | judge i = step i >> sub (incr i) | otherwise = return ()
thru :: Monad m => (v -> m ()) -> v -> m v
thru m v = m v >> return v
inf = maxBound `div` 2 :: Int

main = do
    sn:l <- B.lines <$> B.getContents
    let n = readInt sn
    let (_es,sq:l') = splitAt (n-1) l
    let es = map (map readInt . B.words) _es
    let q = readInt sq
    let qs = map (map readInt . B.words) l'
    putStr $ unlines $ map (printf "%.6f") $ solve n es q qs

solve :: Int -> [[Int]] -> Int -> [[Int]] -> [Double]
solve n es q qs = go cost0 edges0 qs where
    n' :: Integer
    n' = fromIntegral n
    go _ _ [] = []
    go !cost !edges ([ri,wi]:qs) = e : go cost' edges' qs where
        (wi',l) = edges IM.! ri
        e = 3 * fromIntegral cost' / fromIntegral (n' * (n'-1) `div` 2)
        cost' = cost + fromIntegral (wi - wi') * l * (n'-l)
        edges' = IM.insert ri (wi,l) edges
    cost0 = sum $ [ fromIntegral w * l * (n'-l) | (w,l) <- IM.elems edges0 ]
    edges0 = buildTree n es

buildTree :: Int -> [[Int]] -> IM.IntMap (Int,Integer)
buildTree n es = execState doit IM.empty where
    g :: Array Int [(Int,Int,Int)]
    g = accumArray (flip (:)) [] (1,n) $ do
        (i,[a,b,w]) <- zip [1..] es
        [(a,(b,w,i)),(b,(a,w,i))]
    doit = void $ dfs (-1) 1
    dfs pv v = do
        let us = [ (u,w,i) | (u,w,i) <- g ! v, u /= pv]
        fmap ((+1).sum) $ forM us $ \(u,w,i) -> do
            ci <- dfs v u
            modify (IM.insert i (w,ci))
            return ci

import qualified Data.ByteString.Char8 as B
import Data.IntMap hiding (map, foldl)
import qualified Data.IntMap as M
fuck = maybe 0 fst . B.readInt
main = B.interact $ B.unlines . map (B.pack . show) . f . map fuck . B.words
f (n:x) = map (6/z/(z-1)*) $ g s m r where
  z = fromIntegral n
  (p, (q:r)) = splitAt (3*n-3) x
  m = M.map (\(k,l) -> (k*(z-k),l)) $ h p
  s = M.foldl (\a (k,l) -> a+k*fromIntegral l) 0 m
g _ _ [] = []
g s m (r:w:q) = t:g t u q where
  (k,l) = m!r
  t = s-k*fromIntegral(l-w)
  u = adjust (\(k,l) -> (k,w)) r m
h x = fromList . snd $ i [] 0 1 where
  m = j 1 x
  i s u v = foldl f (1,s) $ m!v where
    f x (b,_,_) | b == u = x
    f (x,y) (b,k,l) = let (p,q) = i y v b in (x+p,(k,(fromIntegral p,l)):q)
j _ [] = empty
j k (a:b:l:s) = unionWith (++) (fromList [(a,[(b,k,l)]),(b,[(a,k,l)])]) $ j (k+1) s

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

import Data.List
import Data.Int
import Data.Bits
import Data.Maybe
import Data.Array.Unboxed
import Data.Array.ST
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.ByteString.Char8 as B
import qualified Data.IntMap as IM

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

instance Functor (State s) where
    fmap f m = State $ runState m >>> first f

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

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

get :: State s s
get = State $ id &&& id
put :: s -> State s ()
put = State . const . ((),)
modify :: (s -> s) -> State s ()
modify = State . (.) ((,) ())
evalState :: State s a -> s -> a
evalState = (.) fst . runState
execState :: State s a -> s -> s
execState = (.) snd . runState

readInt = fromJust . fmap fst . B.readInt
readInts = map readInt . B.words <$> B.getLine
readIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine
readLns :: Read a => IO [a]
readLns = map read . words <$> getLine
cmpFst (a,_) (b,_) = compare a b
cmpSnd (_,a) (_,b) = compare a b
cmpLen a b = length a `compare` length b
swap (a,b) = (b,a)
l2p (a:b:_) = (a,b)
p2l (a,b) = [a,b]
itof :: Int -> Double
itof = fromIntegral
defaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e
defaultArray = accumArray $ curry snd
flatten :: [(a,[(b,c)])] -> [((a,b),c)]
flatten = (=<<) $ uncurry $ fmap . first . (,)
stepM_ :: Monad m => a -> (a -> Bool) -> (a -> a) -> (a -> m ()) -> m ()
stepM_ i judge incr step = sub i where
    sub i | judge i = step i >> sub (incr i) | otherwise = return ()
thru :: Monad m => (v -> m ()) -> v -> m v
thru m v = m v >> return v
inf = maxBound `div` 2 :: Int

main = do
    sn:l <- B.lines <$> B.getContents
    let n = readInt sn
    let (_es,sq:l') = splitAt (n-1) l
    let es = map (map readInt . B.words) _es
    let q = readInt sq
    let qs = map (map readInt . B.words) l'
    putStr $ unlines $ map (printf "%.6f") $ solve n es q qs

solve :: Int -> [[Int]] -> Int -> [[Int]] -> [Double]
solve n es q qs = runST doit where
    n' :: Integer
    n' = fromIntegral n
    edges = buildTree n es
    ws = [ fromIntegral w | [_,_,w] <- es ]
    doit :: ST s [Double]
    doit = do
        edgeLength <- newListArray (1,n-1) ws :: ST s (STUArray s Int Int64)
        let cost0 = sum $ zipWith (*) ws (elems edges)
        go cost0 edgeLength qs
    go :: Int64 -> (STUArray s Int Int64) -> [[Int]] -> ST s [Double]
    go _ _ [] = return []
    go !cost edgeLength ([ri,wi]:qs) = do
        wi' <- readArray edgeLength ri
        let e = 3 * fromIntegral cost' / fromIntegral (n' * (n'-1) `div` 2)
            r = edges ! ri
            cost' = cost + fromIntegral (fromIntegral wi - wi') * r
        writeArray edgeLength ri (fromIntegral wi)
        (e:) <$> go cost' edgeLength qs

buildTree :: Int -> [[Int]] -> UArray Int Int64
buildTree n es = doit where
    g :: Array Int [(Int,Int)]
    g = accumArray (flip (:)) [] (1,n) $ do
        (i,[a,b,w]) <- zip [1..] es
        [(a,(b,i)),(b,(a,i))]
    n' = fromIntegral n
    doit = runSTUArray $ do
        a <- newArray_ (1,n-1)
        let dfs pv v = do
            let us = [ (u,i) | (u,i) <- g ! v, u /= pv]
            fmap ((+1).sum) $ forM us $ \(u,i) -> do
                ci <- dfs v u
                writeArray a i (ci * (n'- ci))
                return ci
        dfs (-1) 1
        return a

import Data.IntMap hiding (foldl)
import qualified Data.IntMap as M
main = interact $ unlines . fmap show . f . fmap read . words
f (n:x) = fmap ((* t) . fromIntegral) $ g s m r where
  (p, (q:r)) = splitAt (3*n-3) x
  m = M.map (\(k,l) -> (k*(toInteger n-k),l)) $ h p
  s = M.foldl (\a (k,l) -> a+k*toInteger l) 0 m
  t = 6.0 / (fromIntegral $ n*(n-1))
g _ _ [] = []
g s m (r:w:q) = t:g t u q where
  (k,l) = m!r
  t = s-k*toInteger(l-w)
  u = adjust (\(k,l) -> (k,w)) r m
h x = fromList . snd $ i 0 1 where
  m = j 1 x
  i u v = foldl f (1,[]) $ m!v where
    f x (b,_,_) | b == u = x
    f (x,y) (b,k,l) = let (p,q) = i v b in (x+p,(k,(p,l)):y++q)
j _ [] = empty
j k (a:b:l:s) = unionWith (++) (fromList [(a,[(b,k,l)]),(b,[(a,k,l)])]) $ j (k+1) s


import Control.Monad
import Control.Monad.Trans.Class
import Control.Monad.Trans.State
import qualified Data.ByteString.Builder as B
import qualified Data.ByteString.Char8 as S
import qualified Data.ByteString.Lazy.Char8 as P
import Data.List
import Data.Semigroup
import System.IO

-- Throws exception if not found
findNext :: S.ByteString -> Char -> Int -> Int
findNext s c i = if S.index s i == c then i else findNext s c (i + 1)

firstBeautifulSequence :: S.ByteString -> String -> [Int]
firstBeautifulSequence s t = tail $ scanl (\i c -> findNext s c (i + 1)) (-1) t

main :: IO ()
main = (P.getContents >>=) . evalStateT $ do
  [n, m] <- readInts
  s <- P.toStrict <$> readLine
  t <- P.unpack <$> readLine
  let dpFwd = firstBeautifulSequence s t
      dpRev = reverse (map ((S.length s - 1) -) $ firstBeautifulSequence (S.reverse s) (reverse t))
      answer = maximum $ zipWith (-) (tail dpRev) dpFwd
  putInts [answer]

type SIO = StateT P.ByteString IO

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

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

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

{-# LANGUAGE OverloadedStrings, FunctionalDependencies, FlexibleContexts,
    ConstraintKinds, BangPatterns #-}

import Control.Applicative
import Control.Exception (assert)
import Control.Monad
import Control.Monad.State
import Data.Array.IArray
import Data.Array.Unboxed (UArray)
import Data.Bits
import qualified Data.ByteString.Lazy.Char8 as B
import Data.Char
import Data.Int
import Data.IntMap.Strict (IntMap)
import qualified Data.IntMap.Strict as IntMap
import Data.IntSet (IntSet)
import qualified Data.IntSet as IntSet
import Data.List
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.Maybe
import Data.Monoid
import Data.Ord
import Data.Ratio
import Data.Sequence (Seq)
import qualified Data.Sequence as Seq
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Traversable
import System.IO

------

type Hopper r = State [r]

type HopperT r = StateT [r]

runHopper :: Hopper r a -> [r] -> (a, [r])
runHopper = runState

evalHopper :: Hopper r a -> [r] -> a
evalHopper = evalState

runHopperT :: HopperT r m a -> [r] -> m (a, [r])
runHopperT = runStateT

evalHopperT :: Monad m => HopperT r m a -> [r] -> m a
evalHopperT = evalStateT

type MonadHopper r m = MonadState [r] m

pop :: MonadHopper r m => m (Maybe r)
pop = state f
  where
    f :: [r] -> (Maybe r, [r])
    f [] = (Nothing, [])
    f (q:qs) = (Just q, qs)

popJust :: MonadHopper r m => m r
popJust = fromJust <$> pop

------

popInt :: MonadHopper B.ByteString m => m Int
popInt = fst . fromJust . B.readInt <$> popJust

popInts :: MonadHopper B.ByteString m => m [Int]
popInts = map (fst . fromJust . B.readInt) . B.words <$> popJust

popInteger :: MonadHopper B.ByteString m => m Integer
popInteger = fst . fromJust . B.readInteger <$> popJust

popIntegers :: MonadHopper B.ByteString m => m [Integer]
popIntegers = map (fst . fromJust . B.readInteger) . B.words <$> popJust

------

dropCR :: B.ByteString -> B.ByteString
dropCR s | not (B.null s) && B.last s == '\r' = B.init s
         | otherwise = s

bshow :: Show a => a -> B.ByteString
bshow = B.pack . show

main = B.interact go
  where
    go :: B.ByteString -> B.ByteString
    go = evalHopper run . map dropCR . B.lines

------

run :: Hopper B.ByteString B.ByteString
run = do
  ~[n, m] <- popInts
  s <- B.unpack <$> popJust
  t <- B.unpack <$> popJust
  return $ bshow (solve n m s t) <> "\n"

solve n m s t = maximum $ map (\((a, _), (_, b)) -> b - a) $ adjlist $ zip fi bi
  where
    makeIndex s t = makeIndex' 0 s t

    makeIndex' _ _ [] = []
    makeIndex' i (s : ss) ts@(t : ts')
      | s == t = i : makeIndex' (i + 1) ss ts'
      | otherwise = makeIndex' (i + 1) ss ts

    fi = makeIndex s t

    bi = map ((n - 1 -)) $ reverse $ makeIndex (reverse s) (reverse t)

adjlist as@(_ : as') = zip as as'
adjlist _ = []

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

import Control.Monad
import Control.Monad.Trans.State
import Control.Monad.Trans.Class
import Data.List
import Data.Semigroup

main :: IO ()
main = (P.getContents >>=) . evalStateT $ do
  [n, m] <- readInts
  s <- P.toStrict <$> readLine
  t <- P.unpack <$> readLine
  let
    sfwd c i = if  S.index s i == c  then  i  else  sfwd c (i+1)
    srev c i = if  S.index s i == c  then  i  else  srev c (i-1)
    istart = sfwd (head t) 0
    is = scanl (\i c -> sfwd c (i+1)) istart (tail t)
    trev = reverse t
    jstart = srev (head trev) (n-1)
    js = reverse $ scanl (\j c -> srev c (j-1)) jstart (tail trev)
  putInts [maximum $ zipWith (-) (tail js) is]

type SIO = StateT P.ByteString IO

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

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

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


main = do
  (n:as) <- fmap (map read . words) getContents
  let e = length $ filter even as
  let o = n - e
  print $ if o < e then o else (e + (o-e) `div` 3)

main = do
    (n : as) <- fmap (map read . words) getContents
    let even = length . filter (\x -> x `mod` 2 == 0) $ as
    let odd = length . filter (\x -> x `mod` 2 == 1) $ as
    if even >= odd
    then print $ odd
    else print $ even + ((odd - even) `quot` 3)

--ghc 7.10

evenCount :: [Integer] -> Integer
evenCount [] = 0
evenCount (x:xs)
    | x `mod` 2 == 0 = 1 + evenCount xs
    | otherwise = evenCount xs

oddCount :: [Integer] -> Integer
oddCount [] = 0
oddCount (x:xs)
    | x `mod` 2 == 1 = 1 + oddCount xs
    | otherwise = oddCount xs

main :: IO()
main = do
    str <- getLine
    let n = read str :: Integer
    str <- getLine
    let a = fmap (\as -> read as :: Integer) (words str)
    let ecnt = evenCount a
    let ocnt = oddCount a
    let ans = min ecnt ocnt
    let e1 = ecnt - ans
    let o1 = ocnt - ans
    let a1 = ans + (o1 `div` 3)
    print(a1)

main = do
    (n:as) <- fmap (map read . words) getContents
    print $ (let cnt1 = toInteger $ length $ filter odd as
             in if cnt1 <= (quot n 2) then cnt1
                                       else ((n - cnt1) + (quot (cnt1 - (n - cnt1))) 3))

import System.IO -- импорт  модуля IO
import Data.List
f :: [[Char]] -> Int
f [] = 0
f (x:xs) = if (mod (read x :: Int) 2 == 1) then (1 + (f xs))
    else (f xs)
split :: Char -> String -> [[Char]]
split _ [] = []
split d l = uncurry (:) . fmap (split d . drop 1) . break (==d) $ l
del :: Int -> Int -> Int
del n m = div n m
main :: IO ()
main = do
	n <- getLine
	m <- getLine
	let nech = length [x | (x,y)<- zip (split ' ' m) [1..],(mod (read x :: Int) 2) == 1];ch = length [x | (x,y)<- zip (split ' ' m) [1..], (mod (read x :: Int) 2) == 0];ans = min ch nech + w;w = h (nech - ch)
	print (ans)
    where
        h n = if n < 1 then 0
            else del n 3
	--putStrLn $ show $ (read sx1 :: Int) + (read sx2 :: Int) -- печатаем сумму (преобразовав строки в Int)
	--putStrLn $ show $ n

import Data.List (sort)
main = do
  (n:as) <- fmap (map read . words) getContents
  let oddcnt = length (filter (odd) as)
  print (if oddcnt <= (n - oddcnt) then (oddcnt) else (n - oddcnt + (div (oddcnt - n + oddcnt) 3)))

main = do
  (n:as) <- fmap (map read . words) getContents
  let e = length $ filter even as
  let o = n - e
  print $ if o < e then o else (e + (o-e) `div` 2)

--ghc 7.10

evenCount :: [Integer] -> Integer
evenCount [] = 0
evenCount (x:xs)
    | x `mod` 2 == 0 = 1 + evenCount xs
    | otherwise = evenCount xs

oddCount :: [Integer] -> Integer
oddCount [] = 0
oddCount (x:xs)
    | x `mod` 2 == 1 = 1 + oddCount xs
    | otherwise = oddCount xs

main :: IO()
main = do
    str <- getLine
    let n = read str :: Integer
    str <- getLine
    let a = fmap (\as -> read as :: Integer) (words str)
    let ecnt = evenCount a
    let ocnt = oddCount a
    let ans = ecnt + ((ocnt - ecnt) `div` 3)
    print(ans)

--ghc 7.10

evenCount :: [Integer] -> Integer
evenCount [] = 0
evenCount (x:xs)
    | x `mod` 2 == 0 = 1 + evenCount xs
    | otherwise = evenCount xs

oddCount :: [Integer] -> Integer
oddCount [] = 0
oddCount (x:xs)
    | x `mod` 2 == 1 = 1 + oddCount xs
    | otherwise = oddCount xs

main :: IO()
main = do
    str <- getLine
    let n = read str :: Integer
    str <- getLine
    let a = fmap (\as -> read as :: Integer) (words str)
    let ecnt = evenCount a
    let ocnt = oddCount a
    print(min ecnt ocnt)