import Data.List
import Data.Array
import Data.Function

type Result = Array Int Int

transform :: [Int]->Result
transform (count:xs) = listArray (0,count).reverse$sumX:go xs where
	go [] = []
	go xs'@(h:t) = (sumX - minimum xs'):go (zipWith (+) xs t)
	sumX = sum xs

uB = snd.bounds

best a1 a2 cries = maximum.map calc$[max 0.(cries-).uB$a1..min cries.uB$a2]
	where calc split = a1!(cries-split) + a2!split

merge :: Result->Result->Result
merge a1 a2 = listArray (0,newMax).map (best a1 a2)$[0..newMax]
	where newMax = uB a1 + uB a2

result :: [[Int]]->Int
result ([n,m]:ss) = (!m).foldl1 merge.map transform$ss

main=interact$show.result.map (map read.words).lines

import Data.Array.IO
import Data.Array.IArray ((!),bounds)
import Data.Array.Unboxed (UArray,listArray)
import Control.Monad

import qualified Data.ByteString.Char8 as BS
import Data.ByteString (ByteString)
import Data.Char

readInt :: IO Int
readInt = do line <- BS.getLine
             let Just (n,_) = BS.readInt line
             return n

parseInts :: Int -> ByteString -> [Int]
parseInts k bs | k <= 0 = []
parseInts k bs = case BS.readInt (BS.dropWhile isSpace bs) of
                   Nothing -> []
                   Just (n,bs') -> n : parseInts (k-1) bs'

shelfBest :: [Int] -> UArray Int Int
shelfBest (len:ps) = listArray (0,len) (reverse init)
   where sumX = sum ps
         init = sumX : go ps
         go :: [Int] -> [Int]
         go [] = []
         go xs'@(_:t) = (sumX - minimum xs') : go (zipWith (+) ps t)

upperBound arr = snd $ bounds arr

best:: UArray Int Int -> UArray Int Int -> Int -> Int
best a1 a2 m = maximum $ map go [lo..hi]
  where lo = max 0 (m - upperBound a1)
        hi = min m (upperBound a2)
        go k = a1!(m-k) + a2!k

step :: UArray Int Int -> UArray Int Int -> UArray Int Int
step prev curr = next
  where hi = upperBound prev + upperBound curr
        next = listArray (0,hi) $ map (best prev curr) [0..hi]

solve m shelves =
  let arr = foldl1 step $ map shelfBest shelves
      i = min (upperBound arr) m
      in arr!i

main = do
  (n:m:_) <- fmap (map read . words) getLine
  -- shelves <- replicateM n $ fmap readNums BS.getLine
  shelves <- replicateM n $ fmap (map read . words) getLine
  let answer = solve m shelves
  print answer

import Data.Array
import Control.Monad

type Result = Array Int Int

shelfBest :: [Int] -> Result
shelfBest (len:ps) = listArray (0,len) (reverse init)
   where sumX = sum ps
         init = sumX : go ps
         go :: [Int] -> [Int]
         go [] = []
         go xs'@(_:t) = (sumX - minimum xs') : go (zipWith (+) ps t)

upperBound arr = snd $ bounds arr

best:: Result -> Result -> Int -> Int
best a1 a2 m = maximum $ map go [lo..hi]
  where lo = max 0 (m - upperBound a1)
        hi = min m (upperBound a2)
        go k = a1!(m-k) + a2!k

step :: Result -> Result -> Result
step prev curr = next
  where hi = upperBound prev + upperBound curr
        next = listArray (0,hi) $ map (best prev curr) [0..hi]

solve m shelves =
  let arr = foldl1 step $ map shelfBest shelves
      i = min (upperBound arr) m
      in arr!i

main = do
  (n:m:_) <- fmap (map read . words) getLine
  -- shelves <- replicateM n $ fmap readNums BS.getLine
  shelves <- replicateM n $ fmap (map read . words) getLine
  let answer = solve m shelves
  print answer

import Data.Array.IO
import Data.Array (listArray)
import Data.Array.IArray ((!),bounds)
import Data.Array.Unboxed (UArray)
import Data.Array.MArray (freeze)
import Control.Monad

import qualified Data.ByteString.Char8 as BS
import Data.ByteString (ByteString)
import Data.Char

readInt :: IO Int
readInt = do line <- BS.getLine
             let Just (n,_) = BS.readInt line
             return n

parseInts :: Int -> ByteString -> [Int]
parseInts k bs | k <= 0 = []
parseInts k bs = case BS.readInt (BS.dropWhile isSpace bs) of
                   Nothing -> []
                   Just (n,bs') -> n : parseInts (k-1) bs'

shelfBest m ps = do
  let len = length ps

  let nums = listArray (1,len) ps

  lsums <- newArray (0,m) 0 :: IO (IOUArray Int Int)
  let kmax = min m len
  forM_ [1..kmax] $ \i -> do
    v <- readArray lsums (i-1)
    writeArray lsums i (v+nums!i)

  rsums <- newArray (0,m) 0 :: IO (IOUArray Int Int)
  forM_ [1..kmax] $ \i -> do
    v <- readArray rsums (i-1)
    writeArray rsums i (v+nums!(len+1-i))

  lsums' <- freeze lsums :: IO (UArray Int Int)
  rsums' <- freeze rsums :: IO (UArray Int Int)

  best <- newArray (0,kmax) 0 :: IO (IOUArray Int Int)
  forM_ [1..kmax] $ \k -> do
    let a = maximum [ (lsums'!i) + (rsums'!(k-i)) | i <- [0..k] ]
    writeArray best k a
  freeze best :: IO (UArray Int Int)

step m prev ps = do
  curr <- shelfBest m ps
  let (plo,phi) = bounds prev
  let (clo,chi) = bounds curr
      mmax = min m (chi+phi)
  next <- newArray (0,mmax) 0 :: IO (IOUArray Int Int)
  forM_ [1..mmax] $ \k -> do
    let a = maximum [ (prev!i') + (curr!j') | i <- [0..k], let i' = min i phi, let j' = min (k-i) chi ]
    writeArray next k a
  freeze next :: IO (UArray Int Int)

solve m (ps:rest) = do
  prev <- shelfBest m ps
  let loop arr [] = return arr
      loop arr (ps:pss) = step m arr ps
  arr <- loop prev rest
  let (lo,hi) = bounds arr
      i = min m hi
      answer = arr!i
  return answer

readNums :: ByteString -> [Int]
readNums bs = case BS.readInt (BS.dropWhile isSpace bs) of
                Nothing -> []
                Just (n,bs') -> parseInts n bs'

main = do
  (n:m:_) <- fmap (map read . words) getLine
  shelves <- replicateM n $ fmap readNums BS.getLine
  solve m shelves >>= print


{-# OPTIONS_GHC -O2 -optc-Ofast -fignore-asserts #-}
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ScopedTypeVariables #-}

module Main where

--import Debug.Trace

import System.IO
import GHC.Generics
import Control.Monad
import Control.Monad.ST
import Control.DeepSeq
import Data.Function
import Data.Monoid
import Data.Maybe
import Data.Either
import Data.Ord
import Data.Ratio
import qualified Data.Foldable as Foldable
import Data.Char
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BS8
import Data.List
import Data.Array.IArray
import Data.Array.MArray.Safe
import qualified Data.Array.Unboxed as UA
import qualified Data.Array.ST.Safe as SA
import qualified Data.Array.IO.Safe as IA
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.IntMap.Strict (IntMap)
import qualified Data.IntMap.Strict as IntMap
import Data.Set (Set)
import qualified Data.Set as Set
import Data.IntSet (IntSet)
import qualified Data.IntSet as IntSet

getWords  = words <$> getLine :: IO [String]
getInts = (map (fst . fromJust . BS8.readInt) . BS8.words) <$> BS.getLine :: IO [Int]
getDoubles = (map (read . BS8.unpack) . BS8.words) <$> BS.getLine :: IO [Double]
getInt    = read <$> getLine :: IO Int
getDouble  = read <$> getLine :: IO Double
printLines :: Show a => [a] -> IO ()
printLines = mapM_ print
printStrs = mapM_ putStrLn :: [String] -> IO ()
printList = putStrLn . intercalate " " . map show :: [Int] -> IO ()

---- Answer Code Section ----

type IntArray = Array Int Int
type ByteString = BS8.ByteString
(!.) = BS8.index

getMinSuffix :: ByteString -> ByteString
getMinSuffix str = BS8.drop (pi ! (n - 1)) str where
    n = BS8.length str
    pi = listArray (0, n - 1) $ 0 : [ prefixFunction str pi i | i <- [1 .. n - 1] ]

prefixFunction :: ByteString -> IntArray -> Int -> Int
prefixFunction str pi i = if str !. i == str !. j' then (j' + 1) else j' where
    j = pi ! (i - 1)
    j' = backtrack j
    backtrack k = if k > 0 && str !. i /= str !. k then backtrack (pi ! (k - 1)) else k

process :: ByteString -> ByteString -> ByteString
process s t = let
    suffix = getMinSuffix t
    (sZero, sOne) = countZeroOne s
    (tZero, tOne) = countZeroOne t
    (fZero, fOne) = countZeroOne suffix
    tryWhole = if tZero <= sZero && tOne <= sOne
        then Just (t, (sZero - tZero, sOne - tOne))
        else Nothing
    addSubstr (str, (zero, one)) = Just result where
        mZero = if fZero == 0 then 0 else zero `div` fZero
        mOne = if fOne == 0 then 0 else one `div` fOne
        repCnt = min mZero mOne
        rZero = zero - fZero * repCnt
        rOne = one - fOne * repCnt
        result = str <> BS8.concat (replicate repCnt suffix) <> BS8.replicate rZero '0' <> BS8.replicate rOne '1' in
    case tryWhole >>= addSubstr of
        Just result -> result
        Nothing -> s

countZeroOne str = (zeroCount, oneCount) where
    zeroCount = BS8.count '0' str
    oneCount = BS8.length str - zeroCount

main = do
    s <- nocr <$> BS8.getLine
    t <- nocr <$> BS8.getLine
    BS8.putStrLn $ process s t

nocr str = if BS8.last str == '\r' then BS8.init str else str

module Main where

import Control.Applicative
import Control.Monad.State
import Data.Int
import Data.Maybe
import Data.Semigroup

import qualified Data.ByteString.Lazy.Char8 as BS
import qualified Data.List as L

readLines :: IO [BS.ByteString]
readLines = BS.lines `fmap` BS.getContents

data KmpState a =
  KS a [a] (KmpState a)
  | KM a [a] (KmpState a) (KmpState a)
  | KEND (KmpState a)

kMatch :: Eq a => a -> KmpState a -> Bool
kMatch _ KEND{} = False
kMatch x (KM y _ _ _) = x == y
kMatch x (KS y _ _ ) = x == y

kNext :: KmpState a -> KmpState a
kNext KEND{} = error "Already the end of KMP state."
kNext (KS _ _ n) = n
kNext (KM _ _ _ n) = n

kFail :: KmpState a -> KmpState a
kFail (KEND f) = f
kFail (KM _ _ f _) = f
kFail s@KS{} = s

kFailToList :: (a -> b) -> KmpState a -> [b]
kFailToList f s = case s of
  KEND p -> [f (e p)]
  KS a _ n -> f a : kFailToList f n
  KM _ _ p n -> f (e p) : kFailToList f n
  where
    e KEND{} = error "Impossible"
    e (KS k _ _) = k
    e (KM k _ _ _) = k

kGetSuffix :: KmpState a -> [a]
kGetSuffix KEND{} = []
kGetSuffix (KS _ as _) = as
kGetSuffix (KM _ as _ _) = as

kLast :: KmpState a -> KmpState a
kLast a@KEND{} = a
kLast a = kLast $ kNext a

-- getKmp :: Eq a => [a] -> KmpState a
-- getKmp [] = KEND (getKmp [])
-- getKmp z@(x:xs) = KS x z (kmp' xs self)
--   where
--     self = getKmp z
--
--     kmp' [] curFail = KEND curFail
--     kmp' t@(r:rs) curFail = KM r t curFail (kmp' rs nextFail)
--       where
--         nextFail = tryMatch curFail
--
--         tryMatch st
--           | kMatch r st = kNext st
--           | u@KS{} <- st = u
--           | u@KM{} <- st = tryMatch $ kFail u
--           | KEND{} <- st = error "Try to match end of KMP state"

getKmp :: Eq a => [a] -> KmpState a
getKmp [] = r
  where
    r = KEND r
getKmp z@(x:xs) = q
  where
    q = KS x z $ kmp' xs q

    kmp' [] curFail = KEND curFail
    kmp' t@(r:rs) curFail =  KM r t curFail $ kmp' rs nextFail
      where
        nextFail = tryMatch curFail

        tryMatch st
          | kMatch r st = kNext st
          | u@KS{} <- st = u
          | u@KM{} <- st = tryMatch $ kFail u
          | KEND{} <- st = error "Try to match end of KMP state"

stripWindowsLB :: BS.ByteString -> BS.ByteString
stripWindowsLB a = if BS.isSuffixOf (BS.pack "\r") a
  then fromJust $ BS.stripSuffix (BS.pack "\r") a
  else a

type LineReader a = State [BS.ByteString] a

currentLine :: LineReader BS.ByteString
currentLine = do
  ls <- get
  let (x, xs) = case ls of
        [] -> error "No remain lines."
        l -> (head l, tail l)
  put xs
  return x

restLines :: LineReader [BS.ByteString]
restLines = do
  xs <- get
  put []
  return xs

runLineReader :: LineReader a -> [BS.ByteString] -> (a, [BS.ByteString])
runLineReader reader ls = runState reader (map stripWindowsLB ls)

data Count = C {c0 :: Int32, c1 :: Int32}

getCount :: String -> Count
getCount = L.foldl' inc (C 0 0)
  where
    inc p@(C r0 r1) c = if c == '0' then p{c0 = r0 + 1} else p{c1 = r1 + 1}

toString :: Count -> String
toString (C x y) = replicate (fromIntegral x) '0'
  ++ replicate (fromIntegral y) '1'

solve :: String -> String -> String
solve s t
  | [] <- t = s
  | cs0 < ct0 || cs1 < ct1 = s
  | otherwise = t
      ++ mconcat (replicate numOcc lastSuffix)
      ++ toString crest
  where
    tKmp = getKmp t
    lastSuffix = kGetSuffix $ kFail $ kLast tKmp
    (C ct0 ct1) = getCount t
    (C cs0 cs1) = getCount s
    (C cts0 cts1) = getCount lastSuffix
    numOcc = maybeMin (f cs0 ct0 cts0) (f cs1 ct1 cts1)
    crest = C
      (cs0 - ct0 - cts0 * fromIntegral numOcc)
      (cs1 - ct1 - cts1 * fromIntegral numOcc)
    f cs ct cts = fmap fromIntegral $
      if cts == 0 then Nothing else Just $ (cs - ct) `div` cts

    maybeMin Nothing (Just x) = x
    maybeMin (Just x) Nothing = x
    maybeMin (Just x) (Just y) = min x y

main :: IO ()
main = do
  ls <- readLines
  let ((sl1, sl2), _) = flip runLineReader ls $ do
        rls <- restLines
        case rls of
          l1:l2:_ -> return (BS.unpack l1, BS.unpack l2)
          _ -> error ""
  -- let a = kFailToList id $ getKmp $ zipWith Arg sl2 [1..] :: [Arg Char Int]
  -- print $ map (\(Arg _ b) -> b) a
  putStrLn $ solve sl1 sl2

{-# OPTIONS_GHC -O2 -optc-Ofast -fignore-asserts #-}
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ScopedTypeVariables #-}

module Main where

--import Debug.Trace

import System.IO
import GHC.Generics
import Control.Monad
import Control.Monad.ST
import Control.DeepSeq
import Data.Function
import Data.Monoid
import Data.Maybe
import Data.Either
import Data.Ord
import Data.Ratio
import qualified Data.Foldable as Foldable
import Data.Char
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BS8
import Data.List
import Data.Array.IArray
import Data.Array.MArray.Safe
import qualified Data.Array.Unboxed as UA
import qualified Data.Array.ST.Safe as SA
import qualified Data.Array.IO.Safe as IA
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.IntMap.Strict (IntMap)
import qualified Data.IntMap.Strict as IntMap
import Data.Set (Set)
import qualified Data.Set as Set
import Data.IntSet (IntSet)
import qualified Data.IntSet as IntSet

getWords  = words <$> getLine :: IO [String]
getInts = (map (fst . fromJust . BS8.readInt) . BS8.words) <$> BS.getLine :: IO [Int]
getDoubles = (map (read . BS8.unpack) . BS8.words) <$> BS.getLine :: IO [Double]
getInt    = read <$> getLine :: IO Int
getDouble  = read <$> getLine :: IO Double
printLines :: Show a => [a] -> IO ()
printLines = mapM_ print
printStrs = mapM_ putStrLn :: [String] -> IO ()
printList = putStrLn . intercalate " " . map show :: [Int] -> IO ()

---- Answer Code Section ----

type IntArray = Array Int Int
type ByteString = BS8.ByteString
(!.) = BS8.index

getMinSuffix :: ByteString -> ByteString
getMinSuffix str = BS8.drop (pi ! (n - 1)) str where
    n = BS8.length str
    pi = listArray (0, n - 1) $ 0 : [ prefixFunction str pi i | i <- [1 .. n - 1] ]

prefixFunction :: ByteString -> IntArray -> Int -> Int
prefixFunction str pi i = if str !. i == str !. j' then (j' + 1) else j' where
    j = pi ! (i - 1)
    j' = backtrack j
    backtrack k = if k > 0 && str !. i /= str !. k then backtrack (pi ! (k - 1)) else k

process :: ByteString -> ByteString -> ByteString
process s t = let
    suffix = getMinSuffix t
    (sZero, sOne) = countZeroOne s
    (tZero, tOne) = countZeroOne t
    (fZero, fOne) = countZeroOne suffix
    tryWhole = if tZero <= sZero && tOne <= sOne
        then Just (t, (sZero - tZero, sOne - tOne))
        else Nothing
    addSubstr (str, (zero, one)) = if fZero <= zero && fOne <= one
        then addSubstr ((str <> suffix), (zero - fZero, one - fOne))
        else str <> BS8.replicate zero '0' <> BS8.replicate one '1' in
    case tryWhole >>= return . addSubstr of
        Just result -> result
        Nothing -> s

countZeroOne str = (zeroCount, oneCount) where
    zeroCount = BS8.count '0' str
    oneCount = BS8.length str - zeroCount

main = do
    s <- BS8.getLine
    t <- BS8.getLine
    BS8.putStrLn $ process s t

nocr str = if BS8.last str == '\r' then BS8.init str else str

module Main where

import Control.Applicative
import Control.Monad.State
import Data.Int
import Data.Maybe

import qualified Data.ByteString.Lazy.Char8 as BS
import qualified Data.List as L

readLines :: IO [BS.ByteString]
readLines = BS.lines `fmap` BS.getContents

data KmpState a =
  KS a [a] (KmpState a)
  | KM a [a] (KmpState a) (KmpState a)
  | KEND

kMatch :: Eq a => a -> KmpState a -> Bool
kMatch _ KEND = False
kMatch x (KM y _ _ _) = x == y
kMatch x (KS y _ _ ) = x == y

kNext :: KmpState a -> KmpState a
kNext KEND = error "Already the end of KMP state."
kNext (KS _ _ n) = n
kNext (KM _ _ _ n) = n

kFail :: KmpState a -> KmpState a
kFail KEND = error "Already the end of KMP state."
kFail (KM _ _ f _) = f
kFail s@KS{} = s

kFailToList :: (a -> b) -> KmpState a -> [b]
kFailToList _ KEND = []
kFailToList f (KS a _ n) = f a : kFailToList f n
kFailToList f (KM _ _ p n) = f (e p) : kFailToList f n
  where
    e KEND = error "Impossible"
    e (KS k _ _) = k
    e (KM k _ _ _) = k

kGetSuffix :: KmpState a -> [a]
kGetSuffix KEND = []
kGetSuffix (KS _ as _) = as
kGetSuffix (KM _ as _ _) = as

kLast :: KmpState a -> KmpState a
kLast KEND = KEND
kLast a@(KS _ _ KEND) = a
kLast a@(KM _ _ _ KEND) = a
kLast a = kLast $ kNext a

getKmp :: Eq a => [a] -> KmpState a
getKmp [] = KEND
getKmp y@[x] = KS x y KEND
getKmp z@(x:y:xs) = KS x z (KM y (tail z) self (kmp' xs self))
  where
    self = getKmp z

    kmp' [] _ = KEND
    kmp' t@(r:rs) prevFail = KM r t curFail (kmp' rs curFail)
      where
        curFail = tryMatch prevFail

        tryMatch st
          | kMatch r st = kNext st
          | u@KS{} <- st = u
          | u@KM{} <- st = tryMatch $ kFail u
          | KEND <- st = error "Try to match end of KMP state"

data Count = C {c0 :: Int32, c1 :: Int32}

getCount :: String -> Count
getCount = L.foldl' inc (C 0 0)
  where
    inc p@(C r0 r1) c = if c == '0' then p{c0 = r0 + 1} else p{c1 = r1 + 1}

toString :: Count -> String
toString (C x y) = replicate (fromIntegral x) '0'
  ++ replicate (fromIntegral y) '1'

solve :: String -> String -> String
solve s t
  | [] <- t = s
  | cs0 < ct0 || cs1 < ct1 = s
  | otherwise = t
      ++ mconcat (replicate numOcc lastSuffix)
      ++ toString crest
  where
    tKmp = getKmp t
    lastSuffix = kGetSuffix $ kFail $ kLast tKmp
    (C ct0 ct1) = getCount t
    (C cs0 cs1) = getCount s
    (C cts0 cts1) = getCount lastSuffix
    numOcc = maybeMin (f cs0 ct0 cts0) (f cs1 ct1 cts1)
    crest = C
      (cs0 - ct0 - cts0 * fromIntegral numOcc)
      (cs1 - ct1 - cts1 * fromIntegral numOcc)
    f cs ct cts = fmap fromIntegral $
      if cts == 0 then Nothing else Just $ (cs - ct) `div` cts

    maybeMin Nothing (Just x) = x
    maybeMin (Just x) Nothing = x
    maybeMin (Just x) (Just y) = min x y

stripWindowsLB :: BS.ByteString -> BS.ByteString
stripWindowsLB a = if BS.isSuffixOf (BS.pack "\r") a
  then fromJust $ BS.stripSuffix (BS.pack "\r") a
  else a

type LineReader a = State [BS.ByteString] a

currentLine :: LineReader BS.ByteString
currentLine = do
  ls <- get
  let (x, xs) = case ls of
        [] -> error "No remain lines."
        l -> (head l, tail l)
  put xs
  return x

restLines :: LineReader [BS.ByteString]
restLines = do
  xs <- get
  put []
  return xs

runLineReader :: LineReader a -> [BS.ByteString] -> (a, [BS.ByteString])
runLineReader reader ls = runState reader (map stripWindowsLB ls)

main :: IO ()
main = do
  ls <- readLines
  let ((sl1, sl2), _) = flip runLineReader ls $ do
        rls <- restLines
        case rls of
          [l1, l2] -> return (BS.unpack l1, BS.unpack l2)
          _ -> error ""
  putStrLn $ solve sl1 sl2

module Main where

import Control.Applicative
import Control.Monad.State
import Data.Int
import Data.Maybe
import Data.Semigroup

import qualified Data.ByteString.Lazy.Char8 as BS
import qualified Data.List as L

readLines :: IO [BS.ByteString]
readLines = BS.lines `fmap` BS.getContents

data KmpState a =
  KS a [a] (KmpState a)
  | KM a [a] (KmpState a) (KmpState a)
  | KEND

kMatch :: Eq a => a -> KmpState a -> Bool
kMatch _ KEND = False
kMatch x (KM y _ _ _) = x == y
kMatch x (KS y _ _ ) = x == y

kNext :: KmpState a -> KmpState a
kNext KEND = error "Already the end of KMP state."
kNext (KS _ _ n) = n
kNext (KM _ _ _ n) = n

kFail :: KmpState a -> KmpState a
kFail KEND = error "Already the end of KMP state."
kFail (KM _ _ f _) = f
kFail s@KS{} = s

kFailToList :: (a -> b) -> KmpState a -> [b]
kFailToList _ KEND = []
kFailToList f (KS a _ n) = f a : kFailToList f n
kFailToList f (KM _ _ p n) = f (e p) : kFailToList f n
  where
    e KEND = error "Impossible"
    e (KS k _ _) = k
    e (KM k _ _ _) = k

kGetSuffix :: KmpState a -> [a]
kGetSuffix KEND = []
kGetSuffix (KS _ as _) = as
kGetSuffix (KM _ as _ _) = as

kLast :: KmpState a -> KmpState a
kLast KEND = KEND
kLast a@(KS _ _ KEND) = a
kLast a@(KM _ _ _ KEND) = a
kLast a = kLast $ kNext a

getKmp :: Eq a => [a] -> KmpState a
getKmp [] = KEND
getKmp y@[x] = KS x y KEND
getKmp z@(x:xs) = KS x z (kmp' xs self)
  where
    self = getKmp z

    kmp' [] _ = KEND
    kmp' t@(r:rs) curFail = KM r t curFail (kmp' rs nextFail)
      where
        nextFail = tryMatch curFail

        tryMatch st
          | kMatch r st = kNext st
          | u@KS{} <- st = u
          | u@KM{} <- st = tryMatch $ kFail u
          | KEND <- st = error "Try to match end of KMP state"

stripWindowsLB :: BS.ByteString -> BS.ByteString
stripWindowsLB a = if BS.isSuffixOf (BS.pack "\r") a
  then fromJust $ BS.stripSuffix (BS.pack "\r") a
  else a

type LineReader a = State [BS.ByteString] a

currentLine :: LineReader BS.ByteString
currentLine = do
  ls <- get
  let (x, xs) = case ls of
        [] -> error "No remain lines."
        l -> (head l, tail l)
  put xs
  return x

restLines :: LineReader [BS.ByteString]
restLines = do
  xs <- get
  put []
  return xs

runLineReader :: LineReader a -> [BS.ByteString] -> (a, [BS.ByteString])
runLineReader reader ls = runState reader (map stripWindowsLB ls)

data Count = C {c0 :: Int32, c1 :: Int32}

getCount :: String -> Count
getCount = L.foldl' inc (C 0 0)
  where
    inc p@(C r0 r1) c = if c == '0' then p{c0 = r0 + 1} else p{c1 = r1 + 1}

toString :: Count -> String
toString (C x y) = replicate (fromIntegral x) '0'
  ++ replicate (fromIntegral y) '1'

solve :: String -> String -> String
solve s t
  | [] <- t = s
  | cs0 < ct0 || cs1 < ct1 = s
  | otherwise = t
      ++ mconcat (replicate numOcc lastSuffix)
      ++ toString crest
  where
    tKmp = getKmp t
    lastSuffix = case kGetSuffix $ kNext $ kFail $ kLast tKmp of
      [] -> t
      x -> x
    (C ct0 ct1) = getCount t
    (C cs0 cs1) = getCount s
    (C cts0 cts1) = getCount lastSuffix
    numOcc = maybeMin (f cs0 ct0 cts0) (f cs1 ct1 cts1)
    crest = C
      (cs0 - ct0 - cts0 * fromIntegral numOcc)
      (cs1 - ct1 - cts1 * fromIntegral numOcc)
    f cs ct cts = fmap fromIntegral $
      if cts == 0 then Nothing else Just $ (cs - ct) `div` cts

    maybeMin Nothing (Just x) = x
    maybeMin (Just x) Nothing = x
    maybeMin (Just x) (Just y) = min x y

main :: IO ()
main = do
  ls <- readLines
  let ((sl1, sl2), _) = flip runLineReader ls $ do
        rls <- restLines
        case rls of
          [l1, l2] -> return (BS.unpack l1, BS.unpack l2)
          _ -> error ""
  let a = kFailToList id $ getKmp $ zipWith Arg sl2 [1..] :: [Arg Char Int]
  -- print $ map (\(Arg _ b) -> b) a
  putStrLn $ solve sl1 sl2


module Main where

import Data.Maybe

convert :: String -> String -> Maybe String
convert prev y = if acc == [] then Nothing else Just (minimum acc) where
    acc = filter (>= prev) all
    all = concatMap vars [0 .. 3]
    vars n = map (\c -> take n y ++ c:(drop (n+1) y)) ['0' .. '9']

build :: String -> [String] -> [String]
build _ [] = []
build prev (y:ys) = conv : (build conv ys)
    where conv = fromMaybe "9999" $ convert prev y

solve :: [String] -> Maybe [String]
solve years = if last ans <= "2011" then Just ans else Nothing where
    ans = build "1000" years

main = do
    sn <- getLine
    sYear <- getContents
    let lYear = words sYear
    let ans = solve lYear
    putStrLn $ if ans == Nothing
        then "No solution"
        else unlines (fromMaybe [] ans)

main = interact $ unlines . solve . (map (read :: String -> Int)) . tail . lines
solve xs = if elem 0 ans then ["No solution"] else map show ans
  where ans = solve0 (1000:xs)
solve0 [x] = []
solve0 (x:y:xs) = if null ys then [0] else y':(solve0 (y':xs))
  where ys = filter (check y) [x..2011]
        y' = head ys
check x y = 2>(length $ filter (==False) $ zipWith (==) (show x) (show y))


{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE ScopedTypeVariables #-}
-- {-# LANGUAGE TypeOperators #-}

module Main where

import Data.List
-- import Data.Char
import Data.Maybe
-- import Control.Applicative
import Control.Monad
import System.IO

main :: IO ()
main = do
  -- handle <- openFile "input.txt" ReadMode
  -- contents <- hGetContents handle
  contents <- getContents
  let linesOfFile = lines contents
      t = read $ (linesOfFile !! 0) :: Int
      a = map (\x -> read x :: Int) . words $ (linesOfFile !! 1)
      b = map (\x -> read x :: Int) . words $ (linesOfFile !! 2)
      res = solve a b
    in
    putStrLn $ unwords $ map show $  res

  -- ii <- getLine
  -- aa <- getLine
  -- bb <- getLine
  -- let
  --   nn = map (\x -> read x :: Int) $ words $ ii
  --   n = nn !! 0
  --   k = nn !! 1
  --   a = map (\x -> read x :: Int) $ words $ aa
  --   b = map (\x -> read x :: Int) $ words $ bb

  --   res = solve a b
  --  in
  --   putStrLn res

findDiff _ [] _ = []
findDiff _ _ [] = []
findDiff i (x:xs) (y:ys) =
  if x /= y then i:findDiff (i + 1) xs ys else findDiff (i + 1) xs ys

replaceZero _ [] a = a
replaceZero _ _ [] = []
replaceZero i rr@(r:rs) (a:as) =
  if i == r then 0:replaceZero (i + 1) rs as
  else a:replaceZero (i + 1) rr as

replaceList _ [] = []
replaceList [] a = a
replaceList rr@(r:rs) (a:as) =
  if a == 0 then r:replaceList rs as
  else a:replaceList rr as

solve a b =
  let
    dff = findDiff 0 a b
    aa = replaceZero 0 dff a
    k = [1..length a] \\ aa
    r = replaceList k aa
    r1 = replaceList ([a!!(dff!!0)] ++ [b!!(dff!!1)]) aa
    r2 = replaceList ([b!!(dff!!0)] ++ [a!!(dff!!1)]) aa
    l1 = nub r1

    res = if length dff == 1 then r else
            if length l1 == length a then r1 else r2
  in
    res

import Data.List

doit :: [String] -> [String] -> [String]
doit [] _ = []
doit ("0":xs) (n:ns) = n : doit xs ns
doit (x:xs) ns = x : doit xs ns

valid :: [String] -> [String] -> Bool
valid ans a = (==) 1 . length . filter (uncurry (/=)) . zip ans $ a

main = do
  n <- readLn
  a <- getLine >>= return . words
  b <- getLine >>= return . words
  let numbers = map show $ [1..n] \\ (map (read . fst) . filter (uncurry (==)) . zip a $ b)
  let tmp = map (\(x,y) -> if x == y then x else "0") . zip a $ b
  let ans1 = doit tmp numbers
  let ans2 = doit tmp . reverse $ numbers
  let ans = if valid ans1 a && valid ans1 b then ans1 else ans2
  putStrLn . unwords $ ans

import qualified Data.Set as S

glueWhereZero :: [Int] -> [Int] -> [Int]
glueWhereZero [] b = b
glueWhereZero (x:a) (y:b)
  | y == 0 = x : (glueWhereZero a b)
  | otherwise = y : (glueWhereZero (x:a) b)

main = do
  getLine
  as <- getLine
  bs <- getLine
  let a = map (\x -> read x :: Int) $ words as
  let b = map (\x -> read x :: Int) $ words bs
  let c = map (\x -> if uncurry (==) x then fst x else 0) $ zip a b
  let r = S.toList $ S.difference (S.fromList [1..(length a)]) (S.fromList $ filter (/=0) c)
  let p1 = glueWhereZero r c
  let p2 = glueWhereZero (reverse r) c
  let tmp = length . (filter (uncurry (/=))) . (zip p1)
  putStrLn $ unwords $ map show $ if (tmp a) == 1 && (tmp b) == 1 then p1 else p2

module Main where
import qualified Data.ByteString.Char8 as B
import Control.Monad
import Control.Applicative
import Data.List
import Data.Maybe

readInt = maybe undefined fst . B.readInt
readInts = (readInt <$>) . B.words

solve n as bs = snd $ mapAccumL (\k (a, b) -> if a /= b && a == k && (o || b == m) then (0, m) else (k, a)) k $ zip as bs
  where
    zs = zip as bs
    m = head $ [1..n] \\ as
    k = head $ fromMaybe undefined $ find (\g -> case g of { [_, _] -> True; _ -> False }) $ group $ sort as
    o = case filter (uncurry (/=)) zs of { [_] -> True; _ -> False }

main = do
  n <- readInt <$> B.getLine
  as <- readInts <$> B.getLine
  bs <- readInts <$> B.getLine
  putStr $ unwords $ map show $ solve n as bs

module Main where
import qualified Data.ByteString.Char8 as B
import Control.Monad
import Control.Applicative
import Data.List
import Data.Maybe

readInt = maybe undefined fst . B.readInt
readInts = (readInt <$>) . B.words

solve n as bs = snd $ mapAccumL (\k (a, b) -> if a /= b && a == k && (o || b == m) then (0, m) else (k, a)) (head $ fromMaybe undefined $ find (\g -> case g of { [_, _] -> True; _ -> False }) $ group $ sort as) zs
  where
    zs = zip as bs
    o = case filter (uncurry (/=)) zs of { [_] -> True; _ -> False }
    m = head $ [1..n] \\ as

main = do
  n <- readInt <$> B.getLine
  as <- readInts <$> B.getLine
  bs <- readInts <$> B.getLine
  putStr $ unwords $ map show $ solve n as bs

module Main where
import qualified Data.ByteString.Char8 as B
import Control.Monad
import Control.Applicative
import Data.List
import Data.Maybe

readInt = maybe undefined fst . B.readInt
readInts = (readInt <$>) . B.words

solve n as bs = snd $ mapAccumL (\k (a, b) -> if a /= b && a == k then (0, m) else (k, a)) k $ zip as bs
  where
    m = head $ [1..n] \\ as
    k = head $ fromMaybe undefined $ find (\g -> case g of { [_, _] -> True; _ -> False }) $ group $ sort as

main = do
  n <- readInt <$> B.getLine
  as <- readInts <$> B.getLine
  bs <- readInts <$> B.getLine
  putStr $ unwords $ map show $ solve n as bs

import Data.List

doit :: [String] -> [String] -> [String]
doit [] _ = []
doit ("0":xs) (n:ns) = n : doit xs ns
doit (x:xs) ns = x : doit xs ns

main = do
  n <- readLn
  a <- getLine >>= return . words
  b <- getLine >>= return . words
  let numbers = map show $ [1..n] \\ (map (read . fst) . filter (uncurry (==)) . zip a $ b)
  let tmp = map (\(x,y) -> if x == y then x else "0") . zip a $ b
  putStrLn . unwords $ doit tmp numbers

main = do
  getLine
  a <- getLine >>= return . words
  b <- getLine >>= return . words
  let tmp = filter (uncurry (/=) . fst) . zip (zip a b) $ [0..]
  let numbers = fst . head $ tmp
  let indices = map snd $ tmp
  putStr . unwords . take (head indices) $ a
  putStr $ " " ++ fst numbers ++ " "
  putStr . unwords . take ((head . tail $ indices) - (head indices) - 1) . drop (head indices + 1) $ a
  putStr $ " " ++ snd numbers ++ " "
  putStrLn . unwords . drop ((head . tail $ indices) + 1) $ a

import qualified Data.Set as S

glueWhereZero :: [Int] -> [Int] -> [Int]
glueWhereZero [] b = b
glueWhereZero (x:a) (y:b)
  | y == 0 = x : (glueWhereZero a b)
  | otherwise = y : (glueWhereZero (x:a) b)

main = do
  getLine
  as <- getLine
  bs <- getLine
  let a = map (\x -> read x :: Int) $ words as
  let b = map (\x -> read x :: Int) $ words bs
  let c = map (\x -> if uncurry (==) x then fst x else 0) $ zip a b
  let r = S.toList $ S.difference (S.fromList [1..(length a)]) (S.fromList $ filter (/=0) c)
  let p1 = glueWhereZero r c
  let p2 = glueWhereZero (reverse r) c
  putStrLn $ unwords $ map show $ if (length $ filter (uncurry (/=)) $ zip a p1) == 1 && (length $ filter (uncurry (/=)) $ zip a p2) == 1 then
    p1
    else
      p2


diverse [] n = "NO"
diverse [a] n = if n == 1  then "YES\n"++[a] else "NO"
diverse (a:b:cs) n = if a/=b then "YES\n"++[a,b] else diverse (b:cs) n

main = do
  n <- getLine >>= return . (read :: String -> Int)
  s <- getLine
  putStrLn $ if length s == 1 then "NO" else diverse s n

f::String->String
f []=""
f (x:[])=""
f (x:y:xs)
   |x/=y=(x:y:[])
   |otherwise=f (y:xs)

main = do
       e<-getLine
       e2<-getLine
       let a=f e2
       putStrLn $ if a=="" then "NO" else "YES\n"++a

diverseSubs :: [Char] -> [Char]
diverseSubs (a:[]) = ""
diverseSubs (a:b:rest) = if a /= b
                           then [a,b]
                           else diverseSubs (b:rest)

main :: IO ()
main = do
  n <- getLine
  line <- getLine
  let subline = diverseSubs line
  if subline == ""
    then putStrLn "NO"
    else mapM_ putStrLn ["Yes", subline]

import Data.List
main = do
  getLine
  w <- getLine
  case find f (tails w) of
    Nothing -> putStrLn "NO"
    Just (a:b:_) -> putStrLn "YES" >> putStrLn [a,b]
f (a:b:_) = a /= b
f _ = False

diverse [] n = "NO"
diverse [a] n = if n == 1  then "YES\n"++[a] else "NO"
diverse (a:b:cs) n = if a/=b then "YES\n"++[a,b] else diverse (b:cs) n

main = do
  n <- getLine >>= return . (read :: String -> Int)
  s <- getLine
  putStrLn $ diverse s n

import qualified Data.Set as S
import Data.List
import Control.Arrow
main = do
  l <- readLn
  w <- getLine
  let m = S.fromList $ map (length &&& head) $ group $ sort w
      m' = go l m
  if S.null m' then putStrLn "NO" else do
    putStrLn "YES"
    putStrLn $ intersect' w $ concat (map (uncurry replicate) (S.elems m'))
go l m | Just ((n,c),m') <- S.maxView m, 2*n > l =
           go (l-1) $ if n == 1 then m' else S.insert (n-1,c) m'
       | otherwise = m
intersect' (a:as) bs | a `elem` bs = a : intersect' as (delete a bs)
                     | otherwise = intersect' as bs
intersect' [] _ = []

import qualified Data.Set as S
import Data.List
import Control.Arrow
main = do
  l <- readLn
  w <- getLine
  let m = S.fromList $ map (length &&& head) $ group $ sort w
      m' = go l m
  if S.null m' then putStrLn "NO" else do
    putStrLn "YES"
    putStrLn $ intersect w $ concat (map (uncurry replicate) (S.elems m'))
go l m | Just ((n,c),m') <- S.maxView m, 2*n > l =
           go (l-1) $ if n == 1 then m' else S.insert (n-1,c) m'
       | otherwise = m


{-# OPTIONS_GHC -O2 #-}
{-# LANGUAGE BangPatterns #-}
main = readLn >>= putStr.unlines.map show.solve

solve :: Int -> [Integer]
solve n = take n $ go 1 2
  where
    go !k !x = a : go (k+1) (k * (k+1))
      where
        a :: Integer
        a = k*(k+1)*(k+1)-quot x k

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

readIntList = fmap ((map fn) . B.words) B.getLine :: IO [Integer]
 where fn x = let Just (y,_) = B.readInteger x in y

main = do
    a <- readLn :: IO Integer
    mapM_ print $ go 2 [1..a]

go _ [] = []
go st (l:ls) =
    let prev = st `div` l
        tgt = l*(l+1)*(l+1)
        sq = truncate . sqrt . fromIntegral
    in tgt-prev: go (sq (tgt*l)) ls

{--
import Control.Monad( replicateM_, replicateM, forever)
import Control.Monad.Trans.State( StateT, evalStateT, execStateT, runStateT
			    , get, put)
import Control.Monad.Trans.Writer( WriterT, tell, execWriterT)
import Control.Monad.Trans( lift)
type Level = Int
type State_T = StateT Level (WriterT [Integer] IO) Integer
type Writer_T = WriterT [Integer] IO [Integer]
main = do
    n <- readLn
    let process::Integer -> State_T
	process v = do
	    lv <- get
	    let nextLv = succ lv
		candidate = map fun [1..]
		  where
		    fun l = (l, (nume l) `divMod` toInteger lv)
		    nume l = l^2 * (toInteger nextLv)^2 - v
		(k,resultL) = repack . head $ dropWhile p candidate
		  where
		    repack (l,(d,m)) = (d,l)
		    p (_,(_,m)) = m/=0
	    put nextLv
	    lift $ tell [k]
	    return $ toInteger nextLv * resultL
    let writ::Writer_T
	writ = (`evalStateT` 1) $
		replicateM n . process $ 2
    mapM_ print =<< execWriterT writ
--}
main = do
    n <- readLn
    let l 0 = [2]::[Integer]
	l n = [n,2*n..]
	k n = head $ filter (0<) [m^2 * n' * (n'+1)^2 - l   |
				    m <- [1..]::[Integer]   ,
				    l <- l (n-1)	    ]
	  where n' = toInteger n
    mapM_ (print . k) [1..n]

main = readLn >>= putStr . unlines . map show . solve
solve n = 2 : map (\n -> n * (n + 1)^2 - n + 1) [2 .. n]

main = readLn >>= mapM_ print . solve
solve n = 2 : map (\n -> n * (n + 1)^2 - n + 1) [2 .. n]

import Control.Monad

main :: IO ()
main = do
        x <- readLn :: IO Int
        let ret = take x $ 2:map (\i -> i * (i+1)*(i+1) - (i-1)) [2..] :: [Integer]
        forM_ ret print

main = readLn >>= putStr.unlines.map show.solve

solve :: Integer -> [Integer]
solve n = map f [1..n]
  where
    f 1 = 2
    f x = (x+1)^2 - x


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

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

import qualified Data.Array as A
import qualified Data.Array.MArray.Safe as MA
import qualified Data.Array.IO.Safe as IOA
import qualified Data.Array.ST.Safe as STA
import qualified Data.Array.Unboxed as UA

import Data.Bits
import qualified Data.ByteString.Char8 as B8
import Data.Char
import Data.Int

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

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

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

#ifdef DEBUG
import Debug.Trace (trace, traceM, traceShowM)
debug = flip trace

tracing t x = trace (t ++ " = " ++ show x) x
debugging x t = tracing t x

tracingM t x = traceM $ t ++ " = " ++ show x

#else

debug x _ = x
trace _ x = x
tracing _ x = x
debugging x _ = x

traceM _ = pure ()
tracingM _ _ = pure ()
#endif

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

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

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

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

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

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

{- END OF GENERAL -}

solve :: Int -> [Int] -> Int
solve n as = answer
    where
        g = L.foldl1' gcd as
        answer
            | g == 1 = 0
            | (gcd g n) == 1 = 1
            | (gcd g (n - 1)) == 1 = 2
            | otherwise = 3

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

import System.IO
import Control.Applicative
import Control.Monad
import Data.Char
import Data.List
import Data.Maybe
import Data.Monoid
import Data.Function (fix)
import Data.Array (Array, array, (!))
import Data.Array.ST
import Data.Array.Unboxed
import Control.Monad.ST as ST
import qualified Data.Set as Set
import qualified Data.Map.Strict as Map
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BS8

construct :: (BS.ByteString -> Maybe (a, BS.ByteString)) -> BS.ByteString -> [a]
construct reader str
    | BS.null str = []
    | isSpace (BS8.head str) = construct reader (BS8.tail str)
    | otherwise = let Just (i, other) = reader str in i : construct reader other

getInts :: IO [Int]
getInts = construct BS8.readInt <$> BS.getLine

getIntegers :: IO [Integer]
getIntegers = construct BS8.readInteger <$> BS.getLine

printInts :: [Int] -> IO ()
printInts = putStrLn . unwords . map show

solve xs
    | g == 1 = 0
    | gcd g len == 1 = 1
    | gcd g (len - 1) == 1 = 2
    | otherwise = 3
    where g = foldl gcd 0 xs
          len = length xs

main = do
  [t] <- getInts
  forM_ [1..t] $ \_ -> do
    _ <- getInts
    xs <- getInts
    print $ solve xs