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

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

main :: IO ()
main = do
  n <- (`shiftR` 1) . readInt <$> getLine
  xs <- zip <$> (map (=='1') <$> getLine) <*> (map (=='1') <$> getLine)
  let cnt = A.accumArray (+) 0 ((False,False),(True,True))
            $ map (,1) xs :: UArray (Bool,Bool) Int
      [!c00,!c01,!c10,!c11] = A.elems cnt
      minBnd = maximum [c01 + c11 - n, 0, (c11 - c10 + 1) `shiftR` 1]
      maxBnd = minimum [c00 + c01 + c11 - n, c11, (c01 + c11) `shiftR` 1]
      !p11 = maxBnd
      u = c01 + c11 - 2 * p11
      (!p10,!p01) | u <= c10 = (u,0)
                  | otherwise = (c10, u - c10)
      !p00 = n - c01 - c11 + p11
  if minBnd > maxBnd then print (-1) else
    putStrLn $ unwords $ map show $ go p00 p01 p10 p11 xs
  where
    go !p00 !p01 !p10 !p11 xs = runST $ do
      arr <- A.newListArray ((False,False),(True,True)) [p00,p01,p10,p11]
        :: ST s (STUArray s (Bool,Bool) Int)
      foldr (\(i,x) cont -> do
                ax <- A.readArray arr x
                if ax > 0
                  then do
                    A.writeArray arr x (ax - 1)
                    (i:) <$> cont
                  else cont)
        (return []) (zip [1..] xs)

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

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

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

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

{-# 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.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 ()

---- Answer Code Section ----

process :: [Char] -> [Char] -> Maybe [Int]
process first second = answer >>= Just . indiceList where
    clowns = zip first second
    f11 = (== ('1', '1'))
    f10 = (== ('1', '0'))
    f01 = (== ('0', '1'))
    f00 = (== ('0', '0'))
    fs = [f11, f10, f01, f00]
    ns@[n11, n10, n01, n00] = map (\f -> length $ filter f clowns) fs
    answer = case catMaybes (map (findAnswer ns) [ (x11, x10) | x11 <- [0..n11], x10 <- [0..n10] ]) of
        x:_ -> Just x
        [] -> Nothing
    indices = map (\f -> findIndices f clowns) fs
    indiceList ans = map (+ 1) $ concat $ zipWith take ans indices

findAnswer (n11:n10:n01:n00:[]) (x11, x10) = if valid then Just [x11, x10, x01, x00] else Nothing where
    n = n11 + n10 + n01 + n00
    nPerform = x11 + x10
    x01 = n01 - y01
    x00 = n00 - y00
    y11 = n11 - x11
    y10 = n10 - x10
    y01 = nPerform - y11
    y00 = (n `div` 2) - (y11 + y10 + y01)
    valid = all (>= 0) [x01, x00, y11, y10, y01, y00]

main = do
    n <- getInt
    first <- getLine
    second <- getLine
    putStrLn $ case process first second of
        Just ans -> intercalate " " . map show $ ans
        Nothing -> "-1"

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

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

main :: IO ()
main = do
  n <- (`shiftR` 1) . readInt <$> getLine
  xs <- zip <$> (map (=='1') <$> getLine) <*> (map (=='1') <$> getLine)
  let cnt = A.accumArray (+) 0 ((False,False),(True,True))
            $ map (,1) xs :: UArray (Bool,Bool) Int
      [!c00,!c01,!c10,!c11] = A.elems cnt
      minBnd = maximum [c01 + c11 - n, 0, (c11 - c10 + 1) `shiftR` 1]
      maxBnd = minimum [c00 + c01 + c11 - n, c11, (c01 + c11) `shiftR` 1]
      !p11 = maxBnd
      u = c01 + c11 - 2 * p11
      (!p10,!p01) | u <= c10 = (u,0)
                  | otherwise = (c10, u - c10)
      !p00 = n - c01 - c11 + p11
  print (p00,p01,p10,p11)
  if minBnd > maxBnd then print (-1) else
    putStrLn $ unwords $ map show $ go p00 p01 p10 p11 xs
  where
    go !p00 !p01 !p10 !p11 xs = runST $ do
      arr <- A.newListArray ((False,False),(True,True)) [p00,p01,p10,p11]
        :: ST s (STUArray s (Bool,Bool) Int)
      foldr (\(i,x) cont -> do
                ax <- A.readArray arr x
                if ax > 0
                  then do
                    A.writeArray arr x (ax - 1)
                    (i:) <$> cont
                  else cont)
        (return []) (zip [1..] xs)

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

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

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

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


{-# LANGUAGE ParallelListComp, TypeApplications #-}

import Control.Monad
import Data.Array.Unboxed

-- import GHC.Arr
import System.IO

type Arr = UArray Int Int

fixBuf b = hSetBuffering b (BlockBuffering (Just 65536))

-- import Data.Map ((!))
-- not a change lol
main = do
  fixBuf stdin
  fixBuf stdout
  numCases <- readLn @Int
  replicateM_ numCases $ do
    len <- readLn @Int
    rootList <- fmap (read @Int) . words <$> getLine
    let rootMap =
          array @UArray (1, len) [(i, r) | i <- [1 .. len] | r <- rootList]
    order <- fmap (read @Int) . words <$> getLine
    let orderMap =
          array @UArray (1, len) [(x, i) | x <- order | i <- [0 .. len]]
    -- print (rootMap, orderMap)
    putStrLn $
      if all (\k -> orderMap ! k >= orderMap ! (rootMap ! k)) order
        then ([1 .. len] >>= \k ->
                show (orderMap ! k - orderMap ! (rootMap ! k)) ++ " ")
        else "-1"
  hFlush stdout

{-# LANGUAGE ParallelListComp, TypeApplications #-}

import Control.Monad

-- import Data.Array.Unboxed
import qualified Data.ByteString.Char8 as BS
import Data.Time.Clock.POSIX
import Data.Map.Strict ((!))
import qualified Data.Map.Strict as Map

-- import Data.HashSet
import Data.Maybe

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

readInt :: IO Int
readInt = readLn @Int

-- type Arr = UArray Int Int
-- fixBuf b = hSetBuffering b (BlockBuffering Nothing)
main = do
  numCases <- readInt
  replicateM_ numCases $ do
    len <- readInt
    rootList <- readInts
    order <- readInts
    let rootMap
          -- array @UArray (1, len)
         = Map.fromList [(i, r) | i <- [1 .. len] | r <- rootList]
        orderMap
          -- array @UArray (1, len)
         = Map.fromList [(x, i) | x <- order | i <- [0 .. len]]
    -- print (rootMap, orderMap)
    putStrLn $
      if all (\k -> orderMap ! k >= orderMap ! (rootMap ! k)) order
        then ([1 .. len] >>= \k ->
                show (orderMap ! k - orderMap ! (rootMap ! k)) ++ " ")
        else "-1"

{-# LANGUAGE ParallelListComp, TypeApplications #-}

import Control.Monad

-- import Data.Array.Unboxed
import qualified Data.ByteString.Char8 as BS

import Data.Map.Strict ((!))
import qualified Data.Map.Strict as Map

-- import Data.HashSet
import Data.Maybe

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

readInt :: IO Int
readInt = readLn @Int

-- type Arr = UArray Int Int
-- fixBuf b = hSetBuffering b (BlockBuffering Nothing)
main = do
  numCases <- readInt
  replicateM_ numCases $ do
    len <- readInt
    rootList <- readInts
    order <- readInts
    let rootMap
          -- array @UArray (1, len)
         = Map.fromList [(i, r) | i <- [1 .. len] | r <- rootList]
        orderMap
          -- array @UArray (1, len)
         = Map.fromList [(x, i) | x <- order | i <- [0 .. len]]
    -- print (rootMap, orderMap)
    putStrLn $
      if all (\k -> orderMap ! k >= orderMap ! (rootMap ! k)) order
        then ([1 .. len] >>= \k ->
                show (orderMap ! k - orderMap ! (rootMap ! k)) ++ " ")
        else "-1"

{-# LANGUAGE ParallelListComp, TypeApplications #-}

import Control.Monad

-- import Data.Array.Unboxed
import qualified Data.ByteString.Char8 as BS

import Data.Map ((!))
import qualified Data.Map as Map

-- import Data.HashSet
import Data.Maybe

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

readInt :: IO Int
readInt = readLn @Int

-- type Arr = UArray Int Int
-- fixBuf b = hSetBuffering b (BlockBuffering Nothing)
main = do
  numCases <- readInt
  replicateM_ numCases $ do
    len <- readInt
    rootList <- readInts
    order <- readInts
    let rootMap
          -- array @UArray (1, len)
         = Map.fromList [(i, r) | i <- [1 .. len] | r <- rootList]
        orderMap
          -- array @UArray (1, len)
         = Map.fromList [(x, i) | x <- order | i <- [0 .. len]]
    -- print (rootMap, orderMap)
    putStrLn $
      if all (\k -> orderMap ! k >= orderMap ! (rootMap ! k)) order
        then ([1 .. len] >>= \k ->
                show (orderMap ! k - orderMap ! (rootMap ! k)) ++ " ")
        else "-1"

{-# LANGUAGE ParallelListComp, TypeApplications #-}

import Control.Monad
import Data.Array.Unboxed
import qualified Data.ByteString.Char8 as BS
import Data.Maybe

import System.IO

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

readInt :: IO Int
readInt = readLn @Int

type Arr = UArray Int Int

fixBuf b = hSetBuffering b (BlockBuffering Nothing)

-- import Data.Map ((!))
-- not a change lol 23
main = do
  numCases <- readInt
  replicateM_ numCases $ do
    len <- readInt
    rootList <- readInts
    order <- readInts
    let rootMap =
          array @UArray (1, len) [(i, r) | i <- [1 .. len] | r <- rootList]
        orderMap =
          array @UArray (1, len) [(x, i) | x <- order | i <- [0 .. len]]
    -- print (rootMap, orderMap)
    putStrLn $
      if all (\k -> orderMap ! k >= orderMap ! (rootMap ! k)) order
        then ([1 .. len] >>= \k ->
                show (orderMap ! k - orderMap ! (rootMap ! k)) ++ " ")
        else "-1"

{-# LANGUAGE ParallelListComp, TypeApplications #-}
{-# OPTIONS_GHC -O2 #-}

import Control.Monad
import Data.Array.Unboxed

-- import GHC.Arr
import System.IO

type Arr = UArray Int Int

fixBuf b = hSetBuffering b (BlockBuffering Nothing)

-- import Data.Map ((!))
-- not a change lol 23
main = do
  fixBuf stdin
  fixBuf stdout
  numCases <- readLn @Int
  replicateM_ numCases $ do
    len <- readLn @Int
    rootList <- fmap (read @Int) . words <$> getLine
    let rootMap =
          array @UArray (1, len) [(i, r) | i <- [1 .. len] | r <- rootList]
    order <- fmap (read @Int) . words <$> getLine
    let orderMap =
          array @UArray (1, len) [(x, i) | x <- order | i <- [0 .. len]]
    -- print (rootMap, orderMap)
    putStrLn $
      if all (\k -> orderMap ! k >= orderMap ! (rootMap ! k)) order
        then ([1 .. len] >>= \k ->
                show (orderMap ! k - orderMap ! (rootMap ! k)) ++ " ")
        else "-1"
  hFlush stdout

{-# LANGUAGE ParallelListComp, TypeApplications #-}

import Control.Monad
import Data.Array.Unboxed

-- import GHC.Arr
import System.IO

type Arr = UArray Int Int

fixBuf b = hSetBuffering b (BlockBuffering Nothing)

-- import Data.Map ((!))
-- not a change lol 23
main = do
  fixBuf stdin
  fixBuf stdout
  numCases <- readLn @Int
  replicateM_ numCases $ do
    len <- readLn @Int
    rootList <- fmap (read @Int) . words <$> getLine
    let rootMap =
          array @UArray (1, len) [(i, r) | i <- [1 .. len] | r <- rootList]
    order <- fmap (read @Int) . words <$> getLine
    let orderMap =
          array @UArray (1, len) [(x, i) | x <- order | i <- [0 .. len]]
    -- print (rootMap, orderMap)
    putStrLn $
      if all (\k -> orderMap ! k >= orderMap ! (rootMap ! k)) order
        then ([1 .. len] >>= \k ->
                show (orderMap ! k - orderMap ! (rootMap ! k)) ++ " ")
        else "-1"
  hFlush stdout

{-# LANGUAGE ParallelListComp, TypeApplications #-}

import Control.Monad
import Data.Array.Unboxed

-- import GHC.Arr
import System.IO

type Arr = UArray Int Int

fixBuf b = hSetBuffering b (BlockBuffering Nothing)

-- import Data.Map ((!))
-- not a change lol
main = do
  fixBuf stdin
  fixBuf stdout
  numCases <- readLn @Int
  replicateM_ numCases $ do
    len <- readLn @Int
    rootList <- fmap (read @Int) . words <$> getLine
    let rootMap =
          array @UArray (1, len) [(i, r) | i <- [1 .. len] | r <- rootList]
    order <- fmap (read @Int) . words <$> getLine
    let orderMap =
          array @UArray (1, len) [(x, i) | x <- order | i <- [0 .. len]]
    -- print (rootMap, orderMap)
    putStrLn $
      if all (\k -> orderMap ! k >= orderMap ! (rootMap ! k)) order
        then ([1 .. len] >>= \k ->
                show (orderMap ! k - orderMap ! (rootMap ! k)) ++ " ")
        else "-1"
  hFlush stdout

{-# LANGUAGE ParallelListComp, TypeApplications #-}

import Control.Monad
import Data.Array.Unboxed

-- import GHC.Arr
import System.IO

type Arr = UArray Int Int

fixBuf b = hSetBuffering b (BlockBuffering (Just 65536))

-- import Data.Map ((!))
-- not a change lol
main
  -- fixBuf stdin
  -- fixBuf stdout
 = do
  numCases <- readLn @Int
  replicateM_ numCases $ do
    len <- readLn @Int
    rootList <- fmap (read @Int) . words <$> getLine
    let rootMap =
          array @UArray (1, len) [(i, r) | i <- [1 .. len] | r <- rootList]
    order <- fmap (read @Int) . words <$> getLine
    let orderMap =
          array @UArray (1, len) [(x, i) | x <- order | i <- [0 .. len]]
    -- print (rootMap, orderMap)
    putStrLn $
      if all (\k -> orderMap ! k >= orderMap ! (rootMap ! k)) order
        then ([1 .. len] >>= \k ->
                show (orderMap ! k - orderMap ! (rootMap ! k)) ++ " ")
        else "-1"
  -- hFlush stdout

{-# LANGUAGE ParallelListComp, TypeApplications #-}

import Control.Monad
import GHC.Arr
import System.IO

fixBuf b = hSetBuffering b (BlockBuffering (Just 65536))

-- import Data.Map ((!))
-- not a change lol
main = do
  fixBuf stdin
  fixBuf stdout
  numCases <- readLn @Int
  replicateM_ numCases $ do
    len <- readLn @Int
    rootList <- fmap (read @Int) . words <$> getLine
    let rootMap = array (1, len) [(i, r) | i <- [1 .. len] | r <- rootList]
    order <- fmap (read @Int) . words <$> getLine
    let orderMap = array (1, len) [(x, i) | x <- order | i <- [0 .. len]]
    -- print (rootMap, orderMap)
    putStrLn $
      if all (\k -> orderMap ! k >= orderMap ! (rootMap ! k)) order
        then ([1 .. len] >>= \k ->
                show (orderMap ! k - orderMap ! (rootMap ! k)) ++ " ")
        else "-1"
  hFlush stdout

{-# LANGUAGE ParallelListComp, TypeApplications #-}

import Control.Monad
import GHC.Arr

-- import Data.Map ((!))
main = do
  numCases <- readLn @Int
  replicateM_ numCases $ do
    len <- readLn @Int
    rootList <- fmap (read @Int) . words <$> getLine
    let rootMap = array (1, len) [(i, r) | i <- [1 .. len] | r <- rootList]
    order <- fmap (read @Int) . words <$> getLine
    let orderMap = array (1, len) [(x, i) | x <- order | i <- [0 .. len]]
    -- print (rootMap, orderMap)
    putStrLn $
      if all (\k -> orderMap ! k >= orderMap ! (rootMap ! k)) order
        then ([1 .. len] >>= \k ->
                show (orderMap ! k - orderMap ! (rootMap ! k)) ++ " ")
        else "-1"

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

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

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

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

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

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

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

type WEdge w = (Vertex, (w, Vertex))
type WGraph w = Array Vertex [(w, Vertex)]
data WTree w a = WNode { rootLabelW :: a
                       , subForestW :: [(w, WTree w a)]
                       } deriving Show

buildWG :: Bounds -> [WEdge w] -> WGraph w
buildWG = accumArray (flip (:)) []

dfsWTree :: WGraph w -> Vertex -> WTree w Vertex
dfsWTree g u = go u u where
    go p u = WNode u [(w, go u v) | (w, v) <- g!u, v /= p]

instance Functor (WTree w) where
    fmap f = go where
        go (WNode a ts) = WNode (f a) [(w, go t) | (w, t) <- ts]

getVertexOrder :: Bounds -> [Int] -> UArray Int Int
getVertexOrder bnds p = runSTUArray $ do
  arr <- newArray bnds 0
  forM_ (zip [0..(snd bnds - 1)] p) $ \(i, el) -> do
    writeArray arr el i
  return arr

getEdges' :: forall s. Int -> Bounds -> WTree Int Vertex -> ST s (STUArray s Int Int)
getEdges' root bnds tree = do
  edges <- (newArray bnds 0) :: ST s (STUArray s Int Int)

  let dfs :: Int -> Int -> WTree Int Vertex -> ST s ()
      dfs ww w (WNode v ts) = do
        writeArray edges v (w - ww)
        mapM_ (\(w', subts) -> dfs w w' subts) ts
  dfs 0 0 tree

  return edges

getEdges :: Int -> Bounds -> WTree Int Vertex -> UArray Int Int
getEdges root bnds tree = runSTUArray $ getEdges' root bnds tree

dfsCheckBad :: WTree Int Vertex -> Bool
dfsCheckBad (WNode v ts) = foldr (\(w,all@(WNode u ts')) suf -> suf || v > u || dfsCheckBad all) False ts

printlist = putStrLn . unwords . map show . elems

fita :: IO ()
fita = do
  [n] <- readInts
  mas <- readInts
  p <- readInts

  let vertexOrder = getVertexOrder (1,n) p
      g = buildWG (1,n) $ zipWith (\a b -> (b, (vertexOrder!a,a))) [1..n] mas
      root = fst . fromJust $ (find (\(a,b)->a==b) $ zip [1..n] mas)
      tree = dfsWTree g root

  if (dfsCheckBad ((vertexOrder!) <$> tree))
    then print (-1)
  else
    printlist $ getEdges root (1,n) tree

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

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

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

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

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

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

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

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

type WEdge w = (Vertex, (w, Vertex))
type WGraph w = Array Vertex [(w, Vertex)]
data WTree w a = WNode { rootLabelW :: a
                       , subForestW :: [(w, WTree w a)]
                       } deriving Show

buildWG :: Bounds -> [WEdge w] -> WGraph w
buildWG = accumArray (flip (:)) []

dfsWTree :: WGraph w -> Vertex -> WTree w Vertex
dfsWTree g u = go u u where
    go p u = WNode u [(w, go u v) | (w, v) <- g!u, v /= p]

instance Functor (WTree w) where
    fmap f = go where
        go (WNode a ts) = WNode (f a) [(w, go t) | (w, t) <- ts]

getVertexOrder :: Bounds -> [Int] -> UArray Int Int
getVertexOrder bnds p = runSTUArray $ do
  arr <- newArray bnds 0
  forM_ (zip [0..(snd bnds - 1)] p) $ \(i, el) -> do
    writeArray arr el i
  return arr

getEdges' :: forall s. Int -> Bounds -> WTree Int Vertex -> ST s (STUArray s Int Int)
getEdges' root bnds tree = do
  edges <- (newArray bnds 0) :: ST s (STUArray s Int Int)

  let dfs :: Int -> Int -> WTree Int Vertex -> ST s ()
      dfs p w (WNode v ts) = do
        get_ <- readArray edges p
        writeArray edges v (w - get_)
        mapM_ (\(w, subts) -> dfs v w subts) ts
  dfs root 0 tree

  return edges

getEdges :: Int -> Bounds -> WTree Int Vertex -> UArray Int Int
getEdges root bnds tree = runSTUArray $ getEdges' root bnds tree

dfsCheckBad :: WTree Int Vertex -> Bool
dfsCheckBad (WNode v ts) = foldr (\(w,all@(WNode u ts')) suf -> suf || v > u || dfsCheckBad all) False ts

printlist xs = putStrLn s
  where (' ':s) = foldl (\pref el -> pref++" "++(show el)) "" xs

fita :: IO ()
fita = do
  [n] <- readInts
  mas <- readInts
  p <- readInts

  let vertexOrder = getVertexOrder (1,n) p
      g = buildWG (1,n) $ zipWith (\a b -> (b, (vertexOrder!a,a))) [1..n] mas
      root = fst . fromJust $ (find (\(a,b)->a==b) $ zip [1..n] mas)
      tree = dfsWTree g root

  if (dfsCheckBad ((vertexOrder!) <$> tree))
    then print (-1)
  else
    printlist . elems $ getEdges root (1,n) tree

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

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

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

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

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

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

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

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

type WEdge w = (Vertex, (w, Vertex))
type WGraph w = Array Vertex [(w, Vertex)]
data WTree w a = WNode { rootLabelW :: a
                       , subForestW :: [(w, WTree w a)]
                       } deriving Show

buildWG :: Bounds -> [WEdge w] -> WGraph w
buildWG = accumArray (flip (:)) []

dfsWTree :: WGraph w -> Vertex -> WTree w Vertex
dfsWTree g u = go u u where
    go p u = WNode u [(w, go u v) | (w, v) <- g!u, v /= p]

instance Functor (WTree w) where
    fmap f = go where
        go (WNode a ts) = WNode (f a) [(w, go t) | (w, t) <- ts]

getVertexOrder :: Bounds -> [Int] -> UArray Int Int
getVertexOrder bnds p = runSTUArray $ do
  arr <- newArray bnds 0
  forM_ (zip [0..(snd bnds - 1)] p) $ \(i, el) -> do
    writeArray arr el i
  return arr

getEdges' :: forall s. Int -> Bounds -> WTree Int Vertex -> ST s (STUArray s Int Int)
getEdges' root bnds tree = do
  edges <- (newArray bnds 0) :: ST s (STUArray s Int Int)

  let dfs :: Int -> WTree Int Vertex -> ST s ()
      dfs w (WNode v ts) = do
        get_ <- readArray edges v
        writeArray edges v (w - get_)
        mapM_ (\(w, subts) -> dfs w subts) ts
  dfs 0 tree

  return edges

getEdges :: Int -> Bounds -> WTree Int Vertex -> UArray Int Int
getEdges root bnds tree = runSTUArray $ getEdges' root bnds tree

dfsCheckBad :: WTree Int Vertex -> Bool
dfsCheckBad (WNode v ts) = foldr (\(w,all@(WNode u ts')) suf -> suf || v > u || dfsCheckBad all) False ts

printlist xs = putStrLn s
  where (' ':s) = foldl (\pref el -> pref++" "++(show el)) "" xs

fita :: IO ()
fita = do
  [n] <- readInts
  mas <- readInts
  p <- readInts

  let vertexOrder = getVertexOrder (1,n) p
      g = buildWG (1,n) $ zipWith (\a b -> (b, (vertexOrder!a,a))) [1..n] mas
      root = fst . fromJust $ (find (\(a,b)->a==b) $ zip [1..n] mas)
      tree = dfsWTree g root

  if (dfsCheckBad ((vertexOrder!) <$> tree))
    then print (-1)
  else
    printlist . elems $ getEdges root (1,n) tree

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

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

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

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

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

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

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

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

type WEdge w = (Vertex, (w, Vertex))
type WGraph w = Array Vertex [(w, Vertex)]
data WTree w a = WNode { rootLabelW :: a
                       , subForestW :: [(w, WTree w a)]
                       } deriving Show

buildWG :: Bounds -> [WEdge w] -> WGraph w
buildWG = accumArray (flip (:)) []

dfsWTree :: WGraph w -> Vertex -> WTree w Vertex
dfsWTree g u = go u u where
    go p u = WNode u [(w, go u v) | (w, v) <- g!u, v /= p]

instance Functor (WTree w) where
    fmap f = go where
        go (WNode a ts) = WNode (f a) [(w, go t) | (w, t) <- ts]

getVertexOrder :: Bounds -> [Int] -> UArray Int Int
getVertexOrder bnds p = runSTUArray $ do
  arr <- newArray bnds 0
  forM_ (zip [0..(snd bnds - 1)] p) $ \(i, el) -> do
    writeArray arr el i
  return arr

getEdges' :: forall s. Int -> Bounds -> WTree Int Vertex -> ST s (STUArray s Int Int)
getEdges' root bnds tree = do
  edges <- (newArray bnds 0) :: ST s (STUArray s Int Int)

  let dfs :: Int -> WTree Int Vertex -> ST s ()
      dfs w (WNode v ts) = do
        get_ <- readArray edges v
        writeArray edges v (w - get_)
        mapM_ (\(w, subts) -> dfs w subts) ts
  dfs 0 tree

  return edges

getEdges :: Int -> Bounds -> WTree Int Vertex -> UArray Int Int
getEdges root bnds tree = runSTUArray $ getEdges' root bnds tree

dfsCheckBad :: WTree Int Vertex -> Bool
dfsCheckBad (WNode v ts) = foldr (\(w,all@(WNode u ts')) suf -> suf || v > u || dfsCheckBad all) False ts

fita :: IO ()
fita = do
  [n] <- readInts
  mas <- readInts
  p <- readInts

  let vertexOrder = getVertexOrder (1,n) p
      g = buildWG (1,n) $ zipWith (\a b -> (b, (vertexOrder!a,a))) [1..n] mas
      root = fst . fromJust $ (find (\(a,b)->a==b) $ zip [1..n] mas)
      tree = dfsWTree g root

  if (dfsCheckBad ((vertexOrder!) <$> tree))
    then print (-1)
  else
    print $ elems $ getEdges root (1,n) tree

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


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

main = do
  n <- read <$> getLine
  as <- map read . words <$> getLine
  putStrLn "1 1"
  print (- head as)
  if n == 1
    then putStrLn "1 1\n0\n1 1\n0"
    else do
      putStrLn $ "2 " ++ show n
      let changes = (`mod` n) <$> tail as
      putStrLn $ unwords $ show . (* (n - 1)) <$> changes
      let changed = 0 : zipWith (\a change -> a + (n - 1) * change) (tail as) changes
      putStrLn $ "1 " ++ show n
      putStrLn $ unwords $ show . negate <$> changed

--import Data.List
import Control.Monad
import Data.Int (Int64)

type Operation = (Int64, Int64, [Int64])

main :: IO ()
main = do
  n <- read <$> getLine
  a <- map read . words <$> getLine
  let
    ans :: [Operation]
    ans = case  n  of
      1 -> [(1,1, [0 - head a]), (1, 1, [0]), (1, 1, [0])]
      _ -> let
        p1 = (1, 1, [(n-1) * head a])
        p2 = (2, n, map (* (n-1)) (tail a))
        p3 = (1, n, map (* (0-n)) a)
        in [p1, p2, p3]
  forM_ ans $ \(l, r, incs) -> do
    putStrLn (unwords $ map show [l, r])
    putStrLn (unwords $ map show incs)


import Data.List

addLists :: [Int] -> [Int] -> [Int]
addLists a b = map (\(x, y) -> x + y) $ zip a b

getBest :: [(Int, Int)] -> Int -> Int
getBest [] _ = 400000000
getBest ((a, b) : tail) sz = if sz > a then min b $ getBest tail sz else getBest tail sz

solve :: [Int] -> [Int] -> [(Int, Int)] -> [Int]
solve [] [] [] = []
solve (a : tailA) (b : tailB) c = (getBest c a) : solve tailA tailB ((a, b) : c)
solve _ _ _ = []

main = do
    s <- getLine
    let n = read s :: Int
    s <- getLine
    let szs = map (read :: String -> Int) $ words s
    s <- getLine
    let costs = map (read :: String -> Int) $ words s
    let bestlr = solve szs costs []
    let bestrl = reverse $ solve (reverse $ map negate szs) (reverse costs) []
    let ans = minimum $ addLists costs $ addLists bestlr bestrl
    print $ if ans < 400000000 then ans else -1

module Main where

import Data.Traversable

infinite = 3 * 100000000 + 100

main :: IO ()
main = do
  n <- getLine
  fontsS <- getLine
  let fonts = map (read :: String -> Integer) $ words fontsS
  costsS <- getLine
  let costs = map (read :: String -> Integer) $ words costsS
  print $ solve fonts costs

solve :: [Integer] -> [Integer] -> Integer
solve (f1:f2:fs) (c1:c2:cs) = let answ = tryCost (f2, c2) [(f1,c1)] (zip fs cs) in
                              if answ == infinite
                              then -1
                              else answ

tryCost :: (Integer, Integer) -> [(Integer, Integer)] -> [(Integer, Integer)] -> Integer
tryCost _ _ [] = infinite
tryCost (f,c) left right = min (c + fnd True f left + fnd False f right ) (tryCost (head right) ((f,c):left) (tail right))
  where
  fnd :: Bool -> Integer -> [(Integer, Integer)] -> Integer
  fnd is_l c_font = foldl (\minim (fo,co) -> if co < minim && ((fo < c_font) == is_l) && (fo /= c_font)
                                                 then co
                                                 else minim
                              ) infinite

module Main where

import Data.Traversable

infinite = 3 * 100000000 + 100

main :: IO ()
main = do
  n <- getLine
  fontsS <- getLine
  let fonts = map (read :: String -> Integer) $ words fontsS
  costsS <- getLine
  let costs = map (read :: String -> Integer) $ words costsS
  print $ solve fonts costs

solve :: [Integer] -> [Integer] -> Integer
solve (f1:f2:fs) (c1:c2:cs) = let answ = tryCost (f2, c2) [(f1,c1)] (zip fs cs) in
                              if answ == infinite
                              then -1
                              else answ

tryCost :: (Integer, Integer) -> [(Integer, Integer)] -> [(Integer, Integer)] -> Integer
tryCost _ _ [] = infinite
tryCost (f,c) left right = min (c + (fnd True f left) + (fnd False f right) ) (tryCost (head right) ((f,c):left) (tail right))
  where
  fnd :: Bool -> Integer -> [(Integer, Integer)] -> Integer
  fnd is_l c_font lst = foldl (\minim (fo,co) -> if (co < minim && ((fo < c_font) == is_l) && not (fo == c_font))
                                                 then co
                                                 else minim
                              ) infinite lst

import Data.List

findSmallest :: Int -> [(Int, Int)] -> Int
findSmallest sz scos = foldr (\(s,c) z -> if (s <= sz) then z else if (c < z) then c else z) 1000000009 scos

operate :: [(Int, Int)] -> [Int]
operate [] = []
operate (a:ax) =
    if (ax /= []) then ((findSmallest (fst a) ax) + (snd a)) : operate ax
    else (1000000009):[]

ffst :: (Int, Int, Int) -> Int
ffst (x, _, _) = x

ssnd :: (Int, Int, Int) -> Int
ssnd (_, x, _) = x

thd :: (Int, Int, Int) -> Int
thd (_, _, x) = x

findSmallest2 :: Int -> [(Int, Int, Int)] -> Int
findSmallest2 sz scos = foldr (\(s, _, c) z -> if (s <= sz) then z else if (c < z) then c else z) 1000000009 scos

operate2 :: [(Int, Int, Int)] -> [Int]
operate2 [] = []
operate2 (a:ax) =
    if (ax /= []) then ((findSmallest2 (ffst a) ax) + (ssnd a)) : operate2 ax
    else (1000000009):[]

main :: IO ()
main = do
    inp <- getLine
    let n = read inp :: Int
    sz <- getLine
    let sizes = map read (words sz)
    cs <- getLine
    let costs = map read (words cs)
    -- let sizes = take 3000 [3000, 2999..]
    -- let costs = take 3000 [100000000, 100000000..]
    let comp = operate (zip sizes costs)
    -- print comp
    let comp2 = operate2 (zip3 sizes costs comp)
    -- print comp2
    let res = foldr min 1000000009 comp2
    if (res >= 1000000009) then print (-1)
    else print res
    return ()

import Data.List

findSmallest :: Int -> [(Int, Int)] -> Int
findSmallest sz scos = foldr (\(s,c) z -> if (s <= sz) then z else if (c < z) then c else z) 1000000009 scos

operate :: [(Int, Int)] -> [Int]
operate [] = []
operate (a:ax) =
    if (ax /= []) then
        if (fst (head ax) > fst a) then let res = operate ax in
            if ((head res) < 2 * snd (head ax)) then ((head res) - snd (head ax) + snd a) : res else (snd (head ax) + snd a) : res
        else ((findSmallest (fst a) ax) + (snd a)) : operate ax
    else (1000000009):[]

ffst :: (Int, Int, Int) -> Int
ffst (x, _, _) = x

ssnd :: (Int, Int, Int) -> Int
ssnd (_, x, _) = x

thd :: (Int, Int, Int) -> Int
thd (_, _, x) = x

findSmallest2 :: Int -> [(Int, Int, Int)] -> Int
findSmallest2 sz scos = foldr (\(s, _, c) z -> if (s <= sz) then z else if (c < z) then c else z) 1000000009 scos

operate2 :: [(Int, Int, Int)] -> [Int]
operate2 [] = []
operate2 (a:ax) =
    if (ax /= []) then
        if (ffst (head ax) > ffst a) then let res = operate2 ax in
            if (head res == 1000000009) then ((findSmallest2 (ffst a) ax) + (ssnd a)) : res
            else if ((head res) - ssnd (head ax) < thd (head ax)) then ((head res) - ssnd (head ax) + ssnd a) : res else (thd (head ax) + ssnd a) : res
        else ((findSmallest2 (ffst a) ax) + (ssnd a)) : operate2 ax
    else (1000000009):[]

main :: IO ()
main = do
    inp <- getLine
    let n = read inp :: Int
    sz <- getLine
    let sizes = map read (words sz)
    cs <- getLine
    let costs = map read (words cs)
    let comp = operate (zip sizes costs)
    -- print comp
    let comp2 = operate2 (zip3 sizes costs comp)
    -- print comp2
    let res = foldr min 1000000009 comp2
    if (res >= 1000000009) then print (-1)
    else print res
    return ()


main = do
  x <- readFile "input.txt"
  writeFile "output.txt" (f x)
f x = if (same $ tail $ interval signal) then "YES" else "NO" where
  [n0,signal] = lines x
  first [] = 0
  first ('0':xs)
    | y == 0    = 0
    | otherwise = y + 1
    where y = first xs
  first ('1':_) = 1
  interval [] = []
  interval xs
    | y==0      = []
    | otherwise = y:(interval $ drop y xs)
    where y = first xs
  same [_] = True
  same (y:z:xs) = if y/=z then False else same (z:xs)

import Data.List (findIndices, nub)
import IO

(<?>) :: a -> a -> Bool -> a
(<?>) a b p  =  if p then a else b

on :: (b -> c -> d) -> (a -> b) -> (a -> c) -> (a -> d)
on f g h x  =  f (g x) (h x)

solve :: String -> Bool
solve  =  (<= 1) . length . nub . on (zipWith (-)) id tail . findIndices (== '1')

main :: IO ()
main  =  do
    hInput   <-  openFile "input.txt" ReadMode
    hOutput  <-  openFile "output.txt" WriteMode

    hGetLine hInput >> hGetLine hInput >>= hPutStrLn hOutput . ("YES" <?> "NO") . solve

    hClose hInput
    hClose hOutput

{-# OPTIONS_GHC -O2 -optc-O3 -optc-ffast-math -cpp #-}
{-# OPTIONS_GHC -funbox-strict-fields -fexcess-precision -monly-3-regs #-}
{-# LANGUAGE BangPatterns, OverloadedStrings, ScopedTypeVariables #-}

import Control.Applicative
import Control.Monad
import Data.List
import Text.Printf

main :: IO ()
main = do
  let conv :: String -> [Int]
      conv = map read . words
      writeText = appendFile "output.txt"
  s : ss <- lines <$> readFile "input.txt"
  let signals = reverse . dropWhile (== '0') . reverse . dropWhile (== '0')
              $ head ss
      check n (c : cs)
        | c == '1'  = n : check 0 cs
        | otherwise = check (n + 1) cs
      check n _ = [n]
      zeros = tail . init $ check 0 signals
      ans = (!!) ["NO", "YES"] .  fromEnum . and
          $ zipWith (==) zeros (tail zeros)
  writeText $ printf "%s\n" (ans :: String)

import Prelude
import List
import Char

main = fileInteract q "input.txt" "output.txt"

q = func.lines

func::[String]->String
func (_:b:[]) = solve (map func' b)
                where
                  func'::Char->Int
                  func' a = toInt (a:[])
func _      = ""

fileInteract func inf ouf = do file <- readFile inf
                               writeFile ouf (func file)

toInt::String->Int
toInt = read

asInteger::String->Integer
asInteger = read

toString::Int->String
toString = show

solve::[Int]->String
solve b = case next of
            Nothing -> "NO"
            Just c -> case (solve' c (tail $ dropWhile (/=1) list)) of
                        True  -> "YES"
                        False -> "NO"
          where
            list = tail $ dropWhile (/=1) b
            next = elemIndex 1 list
            solve' a b = case next' of
                           Just c | a == c     -> solve' a $ drop (a+1) b
                                  | otherwise  -> False
                           Nothing             -> True
                    where
                      next' = elemIndex 1 b

import Data.List (nub)
import IO

(<?>) :: a -> a -> Bool -> a
(<?>) a b p  =  if p then a else b

on :: (b -> c -> d) -> (a -> b) -> (a -> c) -> (a -> d)
on f g h x  =  f (g x) (h x)

findIndices :: (a -> Bool) -> [a] -> [Int]
findIndices p xs  =  findIndices' $ zip xs [0..]
  where
    findIndices' []  =  []
    findIndices' ((x, n) : xs)
      | p x  =  n : findIndices' xs
      | otherwise  =  findIndices' xs

solve :: String -> Bool
solve  =  (<= 1) . length . nub . on (zipWith (-)) id tail . findIndices (== '1')

main :: IO ()
main  =  do
    hInput   <-  openFile "input.txt" ReadMode
    hOutput  <-  openFile "output.txt" WriteMode

    hGetLine hInput >>= hPutStrLn hOutput . ("YES" <?> "NO") . solve

    hClose hInput
    hClose hOutput


import           Data.List
import qualified Data.Char as DC
import Control.Monad (replicateM)

leq :: Char -> String -> Int
leq c s = (length $ filter (== c) s)

solveN :: IO Int
solveN = do
    line <- fmap (\x -> (words x) !! 1) getLine
    let val = ((leq 'D' line) - (leq 'U' line)) `mod` 10
    --putStr $ show val
    --putStr " "
    return val

solveCase :: IO ()
solveCase = do
    n <- fmap (read :: String -> Int) getLine
    arr <- fmap (\x -> map (read :: String -> Int) $ words x) getLine
    res <- replicateM n solveN
    putStrLn $ unwords $ map show $ map (\x -> ((fst x) + (snd x)) `mod` 10) $ zip arr res

solve :: Int -> IO ()
solve 0 = do
    return ()
solve cases_left = do
    solveCase
    solve $ cases_left - 1

main = do
    s_testcases <- getLine
    solve $ (read s_testcases :: Int)

import Control.Monad
import Data.List

solveSingle :: Int -> String -> Int
solveSingle n "" = n
solveSingle n ('D':s) =
    solveSingle (n+1) s
solveSingle n ('U':s) =
    solveSingle (n-1) s

solve :: [Int] -> [String] -> [Int]
solve [] [] = []
solve (a:as) (op:ops) =
    ((solveSingle a op) `mod` 10):(solve as ops)

testcase 0 = return ()
testcase t = do
    n <- readLn :: IO Int
    arr <- map (read :: String -> Int) <$> words <$> getLine
    ops <- map (\x -> last $ words x) <$> forM [1..n] (\x -> getLine)
    putStrLn $ unwords $ map show $ solve arr ops
    testcase (t - 1)

main :: IO ()
main = do
    t <- read <$> getLine
    testcase t

import Control.Monad
import Data.List

solve' :: Int -> String -> Int
solve' n "" = n
solve' n ('D':s) =
    solve' (n+1) s
solve' n ('U':s) =
    solve' (n-1) s

solve :: [Int] -> [String] -> [Int]
solve [] [] = []
solve (a:as) (op:ops) =
    ((solve' a op) `mod` 10):(solve as ops)

testcase 0 = return ()
testcase t = do
    n <- readLn :: IO Int
    arr <- map (read :: String -> Int) <$> words <$> getLine
    ops <- map (\x -> last $ words x) <$> forM [1..n] (\x -> getLine)
    putStrLn $ unwords $ map show $ solve arr ops
    testcase (t - 1)

main :: IO ()
main = do
    t <- read <$> getLine
    testcase t

{-# LANGUAGE LambdaCase #-}
module Main where

import Control.Monad (liftM2, replicateM_, replicateM, foldM, when)
import Data.Char (digitToInt, toLower)
import Data.Maybe (fromJust, fromMaybe)
import qualified Data.ByteString.Char8 as C
import Data.Map.Strict (Map, insert, alter, empty, (!), (!?), fromList, fromListWith, mapWithKey, findWithDefault, unionWithKey, traverseWithKey, mapKeys, filterWithKey, mapKeysWith)
import Data.List (group, sort, nub, intercalate)
import Data.Set (Set, deleteFindMin, union)
import qualified Data.Set as Set
import qualified Data.Map.Strict as Map
import Data.Function (on)
-- import System.Random
import Data.Array.MArray (newArray, readArray, writeArray, newListArray)
import Data.Array.IO (IOUArray, getElems)
import Debug.Trace
import Data.Bool (bool)
import Data.Foldable (foldlM)
import Control.Arrow ((&&&))
import Data.String (fromString)

-- road map in reverse, and the number of cities, init pen state
type Domain = ([Int], [Int])
type CoDomain = [Int]
type Solver  = Domain -> CoDomain

readChar8 :: IO [Int]
readChar8 = fmap (fst . fromJust) . fmap C.readInt . C.words <$> fromString <$> getLine

printAns :: CoDomain -> IO ()
printAns xs = putStrLn $ intercalate " " $ map show xs

toNum :: Char -> Int
toNum 'U' = -1
toNum _ = 1

parse :: IO Domain
parse = do
  [n] <- readChar8
  xs <- readChar8
  operations <- replicateM n getLine
  let ops = ((`mod` 10) . sum . map toNum. (!!1). words) <$> operations
  return (xs, ops)

solve :: Solver
solve = uncurry (zipWith (\x y -> (x + y) `mod` 10))

main :: IO ()
main = do
  [n] <- readChar8
  replicateM_ n $ printAns =<< solve <$> parse
  return ()

module Main (main) where
import Numeric (showFFloat)
import Data.Char (toUpper)
import Control.Monad
import qualified Data.Foldable as String

import qualified Data.Set as Set

-- reset && stack build && echo "success" && stack exec haskell-codeforces-exe && echo finished
--  gen-hie > hie.yaml

strToInt a = read a :: Int
strToFloat a = read a :: Float

pshow x = putStr (show x)
pfshow x = putStr (showFFloat (Just 2) x "")

getDelta 'U' = -1
getDelta 'D' = 1

calc :: (Int, String) -> Int
calc (value, changesS) = do
    let changes = last $ words changesS
    let delta = sum $ map getDelta changes
    (value + delta) `mod` 10

solve :: IO()
solve = do
    n <- getLine
    valuesS <- getLine

    let values = map strToInt $ words valuesS
    changes <- replicateM (read n) getLine

    let ff = zip values changes

    let res = map calc ff

    putStrLn $ concatMap ((++ " ") . show) res

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

{-# LANGUAGE ScopedTypeVariables #-}

import Data.List
import Control.Monad
--import Control.Monad.State.Strict

-- parseLine = fmap (map read . words)

toSpaced :: Show a => [a] -> String
toSpaced = intercalate " " . map show

printSpaced :: Show a => [a] -> IO ()
printSpaced = putStrLn . toSpaced

readInt :: IO Int
readInt = fmap read getLine
readInts :: IO [Int]
readInts = fmap (map read . words) getLine

f :: Int -> Int -> Int
f x y = mod (x - y + 10) 10

main :: IO ()
main = do
    t <- readInt
    forM_ [1..t] $ \t -> do
        n <- readInt
        a <- readInts

        offsets <- (forM [1..n] $ \i -> do
            line <- getLine;
            let [b_i_s, s_i] = words line;
            -- print $ (b_i_s, s_i)
            let b_i :: Int = read b_i_s;
            let up_count = (length . filter (=='U')) s_i;
            let down_count = (length . filter (=='D')) s_i;
            return $ up_count - down_count)

        let res :: [Int] = zipWith f a offsets
        printSpaced res
        return ()

import Control.Category ((>>>))
import Control.Monad (replicateM, replicateM_)
import Data.Function ((&))
import Data.Functor ((<&>))

main = do
    tests_n <- getLine <&> read
    replicateM_ tests_n $ do
        wheels_n <- getLine <&> read
        final_wheels <- getLine <&> (words >>> map read)
        wheels_offsets <- replicateM wheels_n $ do
            actions <- getLine <&> words <&> last
            return (count 'U' actions - count 'D' actions)
        let initial_wheels = zipWith (-) final_wheels wheels_offsets & map (`mod` 10)
        putStrLn (initial_wheels & map show & unwords)

count x = filter (== x) >>> length

import Control.Monad
import Data.List

count :: Eq a => a -> [a] -> Int
count elem xs = length (filter (==elem) xs)

solve :: [Int] -> [String] -> [Int]
solve a strs = map (\(x, y) -> (10 + (x - y) `mod` 10) `mod` 10) (zip a b)
    where b = map (\x -> count 'U' x - count 'D' x) strs

testCaseMain :: Int -> IO ()
testCaseMain _ = do n <- (readLn :: IO Int)
                    a <- map (read :: String -> Int) <$> words <$> getLine
                    strs <- map (head . tail . words) <$> forM [1 .. n] (\_ -> getLine)
                    putStrLn (unwords (map show (solve a strs)))

main :: IO ()
main = do n <- (readLn :: IO Int)
          forM_ [1 .. n] testCaseMain

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

import Control.Applicative (Applicative (liftA2))
import Control.Arrow ((>>>))
import Control.Monad (forM_)
import Control.Monad.State (MonadState (get, put), State, evalState, gets, replicateM)
import Data.Array ((!))
import Data.Array.ST (MArray (newArray), readArray, runSTArray, writeArray)
import qualified Data.ByteString.Char8 as C
import Data.Char (toLower)
import Data.List (nub, sort)
import Data.Maybe (fromJust)

data TC = TC {n :: Int, a :: [Int], steps :: [String]}

solve TC {..} = unwords $ fmap show res
  where
    stepsI = fmap (sum . fmap (\case 'U' -> (-1); _ -> 1)) steps
    res = fmap (`mod` 10) $ zipWith (+) a stepsI

main = C.interact $ runScanner scan >>> map solve >>> map (C.pack) >>> C.unlines

scan = numberOf $ do
  n <- int
  a <- n >< int
  steps <- n >< (C.unpack <$> (int >> str))
  pure $ TC n a steps

type Scanner = State [C.ByteString]

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

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

peek :: Scanner C.ByteString
peek = gets head

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

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

integer :: Scanner Integer
integer = read . C.unpack <$> str

double :: Scanner Double
double = read . C.unpack <$> str

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

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

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

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

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

(><) = times

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

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


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

import Control.Applicative
import Control.DeepSeq (deepseq)
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.Ord
import Data.Ratio
import qualified Data.Sequence as Seq
import Data.Sequence (Seq)
import Data.Set (Set)
import Data.STRef
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.Strict (IntMap)
import qualified Data.IntMap.Strict as IntMap
-- import Debug.Trace
import System.IO
import System.Random

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

numLoop :: (Num a, Ord a, Monad m) => a -> a -> (a -> m ()) -> m ()
numLoop start end f = if start <= end then go start else return ()
  where
    go !x | x == end  = f x
          | otherwise = f x >> go (x+1)

{-# INLINE numLoop #-}

qsort gen xs = runSTUArray $ do
    let n = length xs
    a <- newListArray (1, n) xs :: ST s (STUArray s Int Int)
    gr <- newSTRef gen

    let sort' l r = when (l < r) $ do
        g <- readSTRef gr
        let (x, g') = randomR (l, r-1) g
        writeSTRef gr g'

        s <- readArray a x
        let loop i j
              | i > j = return (i, j)
              | otherwise = do
                ai <- readArray a i
                aj <- readArray a j
                case () of
                  _ | ai < s -> loop (i+1) j
                    | aj > s -> loop i (j-1)
                    | otherwise -> do
                        writeArray a i aj
                        writeArray a j ai
                        loop (i+1) (j-1)

        (i, j) <- loop l r

        sort' l j
        sort' i r

    sort' 1 n
    return a

main = do
  n <- readLn
  as <- getInts
  gen <- newStdGen

  let
    as' = map lookup as
      where
        a = qsort gen as

        lookup x = lookup' 1 n
          where
            lookup' l r =
              case compare x (a!m) of
                EQ -> m
                LT -> lookup' l (m-1)
                GT -> lookup' (m+1) r
              where m = (l+r)`div`2

  cnt1 :: IOUArray Int Int <- newArray (1, n) 0
  ls :: IOUArray Int Int <- newArray_ (1, n)
  forM_ (zip [1..n] as') $ \(i, x) -> do
    c <- readArray cnt1 x
    writeArray cnt1 x $ c+1
    writeArray ls i $ c+1

  cnt2 :: IOUArray Int Int <- newArray (1, n) 0
  rs :: IOUArray Int Int <- newArray_ (1, n)
  forM_ (reverse $ zip [1..n] as') $ \(i, x) -> do
    c <- readArray cnt2 x
    writeArray cnt2 x $ c+1
    writeArray rs i $ c+1

  {- let
    acc :: IntMap Int -> Int -> (IntMap Int, Int)
    acc !m a = (m', c)
      where
        !m' = IntMap.insertWith (+) a 1 m
        !c = fromIntegral $ m' IntMap.! a

  ls :: IOUArray Int Int <- newListArray (1, n) $ snd $ mapAccumL acc IntMap.empty as
  rs :: IOUArray Int Int <- newListArray (1, n) $ snd $ mapAccumR acc IntMap.empty as -}

  t :: IOUArray Int Int <- newArray_ (1, n)

  let
    solve l r
      | l == r = return 0
      | otherwise = do
        c1 <- solve l m
        c2 <- solve (m+1) r

        c <- count l (m+1) (0 :: Int64)

        merge ls l m r
        merge rs l m r

        let !s = c1+c2+c
        return s
      where
        m = (l+r) `div` 2

        count i j !c
          | i == m+1 = return c
          | j == r+1 = count (i+1) j $ c + fromIntegral (j-(m+1))
          | otherwise = do
            l <- readArray ls i
            r <- readArray rs j

            if l <= r
              then count (i+1) j $ c + fromIntegral (j-(m+1))
              else count i (j+1) c

        {-# INLINE merge #-}
        merge a l m r = do
            merge' l (m+1) 1

            numLoop 1 (r-l+1) $ \i -> readArray t i >>= writeArray a (l+i-1)
          where
            merge' i j k
              | i == m+1 && j == r+1 = return ()
              | i == m+1 = readArray a j >>= writeArray t k >> merge' i (j+1) (k+1)
              | j == r+1 = readArray a i >>= writeArray t k >> merge' (i+1) j (k+1)
              | otherwise = do
                x <- readArray a i
                y <- readArray a j

                if x <= y
                  then writeArray t k x >> merge' (i+1) j (k+1)
                  else writeArray t k y >> merge' i (j+1) (k+1)

  r <- solve 1 n

  print r

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

import Control.Applicative
import Control.DeepSeq (deepseq)
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.Ord
import Data.Ratio
import qualified Data.Sequence as Seq
import Data.Sequence (Seq)
import Data.Set (Set)
import Data.STRef
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.Strict (IntMap)
import qualified Data.IntMap.Strict as IntMap
-- import Debug.Trace
import System.IO
import System.Random

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

numLoop :: (Num a, Ord a, Monad m) => a -> a -> (a -> m ()) -> m ()
numLoop start end f = if start <= end then go start else return ()
  where
    go !x | x == end  = f x
          | otherwise = f x >> go (x+1)

{-# INLINE numLoop #-}

qsort gen xs = runSTUArray $ do
    let n = length xs
    a <- newListArray (1, n) xs :: ST s (STUArray s Int Int)
    gr <- newSTRef gen

    let sort' l r = when (l < r) $ do
        g <- readSTRef gr
        let (x, g') = randomR (l, r-1) g
        writeSTRef gr g'

        s <- readArray a x
        let loop i j
              | i > j = return (i, j)
              | otherwise = do
                ai <- readArray a i
                aj <- readArray a j
                case () of
                  _ | ai < s -> loop (i+1) j
                    | aj > s -> loop i (j-1)
                    | otherwise -> do
                        writeArray a i aj
                        writeArray a j ai
                        loop (i+1) (j-1)

        (i, j) <- loop l r

        sort' l j
        sort' i r

    sort' 1 n
    return a

main = do
  n <- readLn
  as <- getInts
  gen <- newStdGen

  let
    as' = map lookup as
      where
        a = qsort gen as

        lookup x = lookup' 1 n
          where
            lookup' l r =
              case compare x (a!m) of
                EQ -> m
                LT -> lookup' l (m-1)
                GT -> lookup' (m+1) r
              where m = (l+r)`div`2

  cnt1 :: IOUArray Int Int <- newArray (1, n) 0
  ls :: IOUArray Int Int <- newArray_ (1, n)
  forM_ (zip [1..n] as') $ \(i, x) -> do
    c <- readArray cnt1 x
    writeArray cnt1 x $ c+1
    writeArray ls i $ c+1

  cnt2 :: IOUArray Int Int <- newArray (1, n) 0
  rs :: IOUArray Int Int <- newArray_ (1, n)
  forM_ (reverse $ zip [1..n] as') $ \(i, x) -> do
    c <- readArray cnt2 x
    writeArray cnt2 x $ c+1
    writeArray rs i $ c+1

  {- let
    acc :: IntMap Int -> Int -> (IntMap Int, Int)
    acc !m a = (m', c)
      where
        !m' = IntMap.insertWith (+) a 1 m
        !c = fromIntegral $ m' IntMap.! a

  ls :: IOUArray Int Int <- newListArray (1, n) $ snd $ mapAccumL acc IntMap.empty as
  rs :: IOUArray Int Int <- newListArray (1, n) $ snd $ mapAccumR acc IntMap.empty as -}

  t :: IOUArray Int Int <- newArray_ (1, n)

  let
    solve l r
      | l == r = return 0
      | otherwise = do
        c1 <- solve l m
        c2 <- solve (m+1) r

        c <- count l (m+1) (0 :: Int64)

        merge ls l m r
        merge rs l m r

        return $ c1+c2+c
      where
        m = (l+r) `div` 2

        count i j !c
          | i == m+1 = return c
          | j == r+1 = count (i+1) j $ c + fromIntegral (j-(m+1))
          | otherwise = do
            l <- readArray ls i
            r <- readArray rs j

            if l <= r
              then count (i+1) j $ c + fromIntegral (j-(m+1))
              else count i (j+1) c

        {-# INLINE merge #-}
        merge a l m r = do
            merge' l (m+1) 1

            numLoop 1 (r-l+1) $ \i -> readArray t i >>= writeArray a (l+i-1)
          where
            merge' i j k
              | i == m+1 && j == r+1 = return ()
              | i == m+1 = readArray a j >>= writeArray t k >> merge' i (j+1) (k+1)
              | j == r+1 = readArray a i >>= writeArray t k >> merge' (i+1) j (k+1)
              | otherwise = do
                x <- readArray a i
                y <- readArray a j

                if x <= y
                  then writeArray t k x >> merge' (i+1) j (k+1)
                  else writeArray t k y >> merge' i (j+1) (k+1)

  r <- solve 1 n

  print r

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

import Control.Applicative
import Control.DeepSeq (deepseq)
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.Ord
import Data.Ratio
import qualified Data.Sequence as Seq
import Data.Sequence (Seq)
import Data.Set (Set)
import Data.STRef
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.Strict (IntMap)
import qualified Data.IntMap.Strict as IntMap
-- import Debug.Trace
import System.IO
import System.Random

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

numLoop :: (Num a, Ord a, Monad m) => a -> a -> (a -> m ()) -> m ()
numLoop start end f = if start <= end then go start else return ()
  where
    go !x | x == end  = f x
          | otherwise = f x >> go (x+1)

{-# INLINE numLoop #-}

qsort gen xs = runSTUArray $ do
    let n = length xs
    a <- newListArray (1, n) xs :: ST s (STUArray s Int Int)
    gr <- newSTRef gen

    let sort' l r = when (l < r) $ do
        g <- readSTRef gr
        let (x, g') = randomR (l, r-1) g
        writeSTRef gr g'

        s <- readArray a x
        let loop i j
              | i > j = return (i, j)
              | otherwise = do
                ai <- readArray a i
                aj <- readArray a j
                case () of
                  _ | ai < s -> loop (i+1) j
                    | aj > s -> loop i (j-1)
                    | otherwise -> do
                        writeArray a i aj
                        writeArray a j ai
                        loop (i+1) (j-1)

        (i, j) <- loop l r

        sort' l j
        sort' i r

    sort' 1 n
    return a

main = do
  n <- readLn
  as <- getInts
  gen <- newStdGen

  let
    as' = map lookup as
      where
        a = qsort gen as

        lookup x = lookup' 1 n
          where
            lookup' l r =
              case compare x (a!m) of
                EQ -> m
                LT -> lookup' l (m-1)
                GT -> lookup' (m+1) r
              where m = (l+r)`div`2

  cnt1 :: IOUArray Int Int <- newArray (1, n) 0
  ls :: IOUArray Int Int <- newArray_ (1, n)
  forM_ (zip [1..n] as') $ \(i, x) -> do
    c <- readArray cnt1 x
    writeArray cnt1 x $ c+1
    writeArray ls i $ c+1

  cnt2 :: IOUArray Int Int <- newArray (1, n) 0
  rs :: IOUArray Int Int <- newArray_ (1, n)
  forM_ (reverse $ zip [1..n] as') $ \(i, x) -> do
    c <- readArray cnt2 x
    writeArray cnt2 x $ c+1
    writeArray rs i $ c+1

  {- let
    acc :: IntMap Int -> Int -> (IntMap Int, Int)
    acc !m a = (m', c)
      where
        !m' = IntMap.insertWith (+) a 1 m
        !c = fromIntegral $ m' IntMap.! a

  ls :: IOUArray Int Int <- newListArray (1, n) $ snd $ mapAccumL acc IntMap.empty as
  rs :: IOUArray Int Int <- newListArray (1, n) $ snd $ mapAccumR acc IntMap.empty as -}

  t :: IOUArray Int Int <- newArray_ (1, n)

  let
    solve l r
      | l == r = return 0
      | otherwise = do
        c1 <- solve l m
        c2 <- solve (m+1) r

        c <- count l (m+1) (0 :: Int64)

        merge ls l m r
        merge rs l m r

        return $ c1+c2+c
      where
        m = (l+r) `div` 2

        count i j !c
          | i == m+1 = return c
          | j == r+1 = count (i+1) j $ c + fromIntegral (j-(m+1))
          | otherwise = do
            l <- readArray ls i
            r <- readArray rs j

            if l <= r
              then count (i+1) j $ c + fromIntegral (j-(m+1))
              else count i (j+1) c

        merge a l m r = do
            merge' l (m+1) 1

            numLoop 1 (r-l+1) $ \i -> readArray t i >>= writeArray a (l+i-1)
          where
            merge' i j k
              | i == m+1 && j == r+1 = return ()
              | i == m+1 = readArray a j >>= writeArray t k >> merge' i (j+1) (k+1)
              | j == r+1 = readArray a i >>= writeArray t k >> merge' (i+1) j (k+1)
              | otherwise = do
                x <- readArray a i
                y <- readArray a j

                if x <= y
                  then writeArray t k x >> merge' (i+1) j (k+1)
                  else writeArray t k y >> merge' i (j+1) (k+1)

  r <- solve 1 n

  print r

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

import Control.Applicative
import Control.DeepSeq (deepseq)
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.Ord
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.Strict (IntMap)
import qualified Data.IntMap.Strict 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
  as <- getInts

  let
    as' = map lookup as
      where
        a :: UArray Int Int = listArray (1, n) $ sort as

        lookup x = lookup' 1 n
          where
            lookup' l r
              | x == v = m
              | x < v = lookup' 1 (m-1)
              | x > v = lookup' (m+1) r
              where
                m = (l+r)`div`2
                v = a!m

  cnt1 :: IOUArray Int Int <- newArray (1, n) 0
  ls :: IOUArray Int Int <- newArray_ (1, n)
  forM_ (zip [1..n] as') $ \(i, x) -> do
    c <- readArray cnt1 x
    writeArray cnt1 x $ c+1
    writeArray ls i $ c+1

  cnt2 :: IOUArray Int Int <- newArray (1, n) 0
  rs :: IOUArray Int Int <- newArray_ (1, n)
  forM_ (reverse $ zip [1..n] as') $ \(i, x) -> do
    c <- readArray cnt2 x
    writeArray cnt2 x $ c+1
    writeArray rs i $ c+1

  t :: IOUArray Int Int <- newArray_ (1, n)

  let
    solve l r
      | l == r = return 0
      | otherwise = do
        c1 <- solve l m
        c2 <- solve (m+1) r

        c <- count l (m+1) 0

        merge ls l m r
        merge rs l m r

        return $ c1+c2+c
      where
        m = (l+r) `div` 2

        count i j c
          | i == m+1 = return c
          | j == r+1 = count (i+1) j $ c + j-(m+1)
          | otherwise = do
            l <- readArray ls i
            r <- readArray rs j

            if l <= r
              then count (i+1) j $ c + j-(m+1)
              else count i (j+1) c

        merge a l m r = do
            merge' l (m+1) 1

            forM_ [1..r-l+1] $ \i -> readArray t i >>= writeArray a (l+i-1)
          where
            merge' i j k
              | i == m+1 && j == r+1 = return ()
              | i == m+1 = readArray a j >>= writeArray t k >> merge' i (j+1) (k+1)
              | j == r+1 = readArray a i >>= writeArray t k >> merge' (i+1) j (k+1)
              | otherwise = do
                x <- readArray a i
                y <- readArray a j

                if x <= y
                  then writeArray t k x >> merge' (i+1) j (k+1)
                  else writeArray t k y >> merge' i (j+1) (k+1)

  r <- solve 1 n

  print r


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

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

type EIO a = ExceptT String IO a

data HNormal
data HString
data HList

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

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

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

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

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

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

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

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

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

main_ :: EIO ()
-- template --
main_ = do
    s <- get
    let k = f1 s in do
        putln $ length k
        f2 k

f1 :: String -> [(Int, [Int])]
f1 s = let sa = array (1, length s) (zip [1..length s] s) :: UArray Int Char in
       let ll = filter (\i -> sa ! i == '(') [1..length s] in
       let rl = filter (\i -> sa ! i == ')') $ reverse [1..length s] in
       let lrpair = filter (\(i, j) -> i < j) $ zip ll rl in
       let (newl, newr) = unzip lrpair in
       let newi =  (++) newl $ reverse newr in
       let (news, _) = foldl (\(s, l) i ->
            case l of
               x : xs -> if x == i then (s, xs) else ((sa ! i) : s, l)
               [] -> ((sa ! i) : s, [])
            ) ([], newi)  [1..length s] in
       if length newi == 0 then
           []
        else
           (length newi, newi) : (f1 $ reverse news)

f2 :: [(Int, [Int])] -> EIO ()
f2 [] = return ()
f2 ((k, l) : r) = do
    putln k
    putln l
    f2 r

--import Control.Monad
--import Data.List
--import Data.Function

main :: IO ()
main = routine

routine :: IO ()
routine = do
  s <- getLine
  if end s
    then
      putStrLn "0"
    else
      do
        putStrLn "1"
        let
          answer = solve s
          in do
            print $ length answer
            putStrLn $ (unwords.map show) answer

solve :: String -> [Int]
solve s = take m offene ++ reverse (take m (reverse geschlossene))
  where
    zipped = zip s [(1::Int)..]
    offene = map snd $ filter (\(a,_) -> a=='(') zipped
    geschlossene = map snd $ filter (\(a,_) -> a==')') zipped
    s1 = scanl (\acc ch -> acc + fromEnum (ch == '(')) 0 s
    s2 = reverse $ scanr (\ch acc -> acc + fromEnum (ch == ')')) 0 s
    m = maximum $ zipWith min s1 (reverse s2)

end :: String -> Bool
end s = all (== '(') $ dropWhile (== ')') s

--import Control.Monad
--import Data.List
--import Data.Function

main :: IO ()
main = routine

routine :: IO ()
routine = do
  s <- getLine
  if end s
    then
      putStrLn "0"
    else
      do
        putStrLn "1"
        let
          answer = solve s
          in do
            print $ length answer
            putStrLn $ (unwords.map show) answer

solve :: String -> [Int]
solve s = take m offene ++ take m (reverse geschlossene)
  where
    zipped = zip s [(1::Int)..]
    offene = map snd $ filter (\(a,_) -> a=='(') zipped
    geschlossene = map snd $ filter (\(a,_) -> a==')') zipped
    s1 = scanl (\acc ch -> acc + fromEnum (ch == '(')) 0 s
    s2 = reverse $ scanr (\ch acc -> acc + fromEnum (ch == ')')) 0 s
    m = maximum $ zipWith min s1 (reverse s2)

end :: String -> Bool
end s = all (== '(') $ dropWhile (== ')') s


import Data.Char (ord,chr)
import Control.Monad    --ord Char->Int , chr Int ->Char

intercal :: [Char] -> Int -> [Int]
intercal [] n = []
intercal (x:xs) n = let k =  transform x
                 in value k : intercal xs k
  where
    transform = toDec.length8. toBi.ord
    value k = (n - k) `mod` 256

length8 :: String -> String
length8 xs = xs ++ replicate (8-length xs) '0'

--10�i������2�i����(�t��)
toBi :: Int -> String
toBi 0 = "0"
toBi n = show (mod n 2) ++ toBi (div n 2)

--2�i������10�i����
toDec :: String -> Int
toDec [] = 0
toDec ('0':cs) = toDec cs
toDec ('1':cs) = 2^(length cs) + toDec cs

main = do xs <- getLine
          forM_ (intercal xs 0) print

import Data.Bits
import Data.Char
import Data.Word
import Data.Function

main=getLine>>=mapM print.solve.(0:).map (toEnum.ord)

solve :: [Word8] -> [Word8]
solve cs = zipWith ((-)`on`rev) cs (tail cs)

rev :: Word8 -> Word8
rev n = foldl setBit 0 [ 7-i | i<-[0..7], testBit n i]

r 0 c n=c
r i c n=r(i-1)(c*2+n`mod`2)$n`div`2
f l=zipWith(-)(0:l)l
main=interact$unlines.map(show.(`mod`256)).f.map(r 8 0.fromEnum).init

toBits 0 n = []
toBits i n = (n `mod` 2) : toBits (i-1) (n `div` 2)

fromBits [] = 0
fromBits (h:t) = 2*fromBits t + h

rev = fromBits . reverse . toBits 8

recover l = zipWith (-) (0:l) l

to256 = map (`mod` 256)
s[l]=to256 $ recover (map (rev.fromEnum) l)
main=interact$unlines.map show.s.lines

module Main where

import Data.Char

main = interact (unlines . solve . head. lines)

solve :: String -> [String]
solve line = map show $ getArray (0 : (map ord line))

getArray :: [Int] -> [Int]
getArray [_] = []
getArray (x : (t@(y:_))) = (mirror x - mirror y) `trueMod` 256 : getArray t

trueMod :: Int -> Int -> Int
trueMod x y =
    let m = x `mod` y in
        if m < 0 then m + y else m

mirror = bin2num . reverse . num2bin

bin2num = foldl (\x y -> 2 * x + y) 0

num2bin = reverse . (num2bin' 8)

num2bin' 0 x = []
num2bin' n x = x `mod` 2 : num2bin' (n - 1) (x `div` 2)

import Data.List
import Data.Char

reverseBits :: Int -> Int
reverseBits n = snd $ foldl' collect (n, 0) [1 .. 8]
  where collect (n, res) _ = (n `div` 2,
                              res * 2 + n `mod` 2)

solve :: String -> [Int]
solve text = map handle xs
  where xs = zip (0:map ord text) $ map ord text
        handle (last, x) =
          (reverseBits last - reverseBits x) `mod` 256

main = do text <- getLine
          sequence_ $ map print $ solve text

{-# LANGUAGE TypeSynonymInstances #-}
{-# OPTIONS_GHC -O2 #-}
{-# LANGUAGE ForeignFunctionInterface, ScopedTypeVariables #-}
{-# LANGUAGE OverloadedStrings #-}
import Foreign
import Foreign.C.Types
import Foreign.C.String
import Foreign.Marshal.Alloc
import Debug.Trace
import Data.List
import Control.Monad
import Control.Monad.ST
import qualified Data.Array.Unboxed as UB
import Data.Array.ST
import Data.Array
import Data.Char
import Data.Bits
class IOtyp a where scan' :: String -> a; show' :: a -> String
instance IOtyp Int where scan' = read; show' = show
instance IOtyp Char where scan' (x:_) = x;show' = (:[])
instance IOtyp Float where scan' = read;show' = show
instance IOtyp Double where scan' = read;show' = show
instance IOtyp Integer where scan' = read;show' = show
instance IOtyp String where scan' = id;show' = id
instance (IOtyp a,IOtyp b) => IOtyp (a,b) where scan' = (\(x:y:_) -> (scan' x,scan' y)).words;show' (x,y) = show' x++' ':show' y
instance (IOtyp a,IOtyp b,IOtyp c) => IOtyp (a,b,c) where scan' = (\(x:y:z:_) -> (scan' x,scan' y,scan' z)).words;show' (x,y,z) = show' x++' ':show' y++' ':show' z
foreign import ccall "stdio.h puts" c_puts :: CString -> IO ()
scan :: (IOtyp a) => IO a; scan = getLine>>=return.scan'
scans :: (IOtyp a) => Int -> IO [a]; scans = (flip replicateM) scan
scanlist :: (IOtyp a) => IO [a]; scanlist = getLine>>=return.map scan'.words
scanlists :: (IOtyp a) => Int -> IO [[a]]; scanlists = (flip replicateM) scanlist
puts :: (IOtyp a) => a -> IO (); puts ans = do {str<-newCString $ show' ans;c_puts str;free str}

ind :: Bool -> Int
ind b = if b then 1 else 0

reverseBin :: Int -> Int
reverseBin bin =
    (
     (ind (testBit bin 7))+
     (ind (testBit bin 6))*2+
     (ind (testBit bin 5))*4+
     (ind (testBit bin 4))*8+
     (ind (testBit bin 3))*16+
     (ind (testBit bin 2))*32+
     (ind (testBit bin 1))*64+
     (ind (testBit bin 0))*128
    )

convToINTERCAL :: Char -> Int
convToINTERCAL c =
    let n = ord c
    in
      (512-(reverseBin n))

solve :: String -> [Int]
solve str = rec 0 str []
    where
      rec _ [] l = reverse l
      rec prev (x:xs) l = rec (reverseBin (ord x)) xs ((mod ((convToINTERCAL x)+prev) 256):l)

main = getLine >>= puts.unlines.map show.solve

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

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

parseInput = do
    BS.unpack <$> readLine
  where
    readInt = state $ fromJust . BS.readInt . BS.dropWhile isSpace
    readInteger = state $ fromJust . BS.readInteger . BS.dropWhile isSpace
    readString = state $ BS.span (not . isSpace) . BS.dropWhile isSpace
    readLine = state $ BS.span (not . isEoln) . BS.dropWhile isEoln
    isEoln ch = ch == '\r' || ch == '\n'

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

solve s = BS.unlines $ map (BS.pack . show ) $ go 0 (map ord s)

revbits a = sum [((a `shiftR` i) .&. 1) `shiftL` (7 - i) | i <- [0..7]]

go _ [] = []
go p (x:xs) = (p' - x') `mod` 256 : go x xs
  where
    p' = revbits p
    x' = revbits x

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

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

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

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

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

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

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

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

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

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

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

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

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

state = State

import Data.Bits
import Data.Char
import Data.Word
import Data.Function

main=interact $ unlines.map show.solve.(0:).map (toEnum.ord)

solve :: [Word8] -> [Word8]
solve cs = zipWith ((-)`on`rev) cs (tail cs)

rev :: Word8 -> Word8
rev n = foldl setBit 0 [ 7-i | i<-[0..7], testBit n i]


{-# LANGUAGE Safe #-}
{-# Options_GHC -O3 #-}
import Data.ByteString.Builder
import Data.Monoid
import System.IO
import qualified Data.ByteString.Char8 as C
import Data.Char
import Data.Array.Unboxed
import qualified Data.Sequence as S
import Data.Foldable
import Data.List
import Data.Ratio
import Data.Int

ru, ri :: C.ByteString -> Int

ru = C.foldl' (\a c -> a * 10 - 48 + ord c) 0
ri s
  | C.head s == '-' = negate $ ru $ C.tail s
  | otherwise = ru s

test :: Int -> [Int] -> Int
test n l = r1 + r2
  where
    (a, l') = splitAt n l
    b = take n l'
    x = zip a b
    r2 = maximum $ (0 : ) $ map length $ group $ toList $ S.unstableSort $ S.fromList [ (fromIntegral j) % (fromIntegral i) :: Ratio Int64 | (i, j) <- x, i /= 0]
    r1 = length $ filter (\(i, j) -> i == 0 && j == 0) x

main = do
  s <- C.getContents
  let (n:a) = map ri $ C.words s
  print $ test n a

{-# LANGUAGE Safe #-}
{-# Options_GHC -O3 #-}
import Data.ByteString.Builder
import Data.Monoid
import System.IO
import qualified Data.ByteString.Char8 as C
import Data.Char
import Data.Array.Unboxed
import qualified Data.Sequence as S
import Data.Foldable
import Data.List
import Data.Ratio
import Data.Int

ru, ri :: C.ByteString -> Int

ru = C.foldl' (\a c -> a * 10 - 48 + ord c) 0
ri s
  | C.head s == '-' = negate $ ru $ C.tail s
  | otherwise = ru s

test :: Int -> [Int] -> Int
test n l = max (r1 + r2) r3
  where
    (a, l') = splitAt n l
    b = take n l'
    x = zip a b
    r2 = maximum $ (0 : ) $ map length $ group $ toList $ S.unstableSort $ S.fromList [ (fromIntegral j) % (fromIntegral i) :: Ratio Int64 | (i, j) <- x, i /= 0]
    r1 = length $ filter (\(i, j) -> i == 0 && j == 0) x
    r3 = length $ filter (== 0) b

main = do
  s <- C.getContents
  let (n:a) = map ri $ C.words s
  print $ test n a

{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ScopedTypeVariables #-}

module Main where

--import Debug.Trace

import System.IO
import Control.Monad
import Control.Monad.ST
import Control.DeepSeq
import Data.Function
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.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 ()

---- Answer Code Section ----

divide a b
    | a == 0 && b /= 0 = Nothing
    | b == 0 = Just 0
    | otherwise = Just (fromIntegral a % fromIntegral b)

process :: [Int] -> [Int] -> Int
process as bs = maxCount ds where
    ds = catMaybes $ zipWith divide as bs :: [Rational]
    n = length ds
    maxCount = maximum' . map lengthPlusWc . group . sort
    maximum' [] = 0
    maximum' l  = maximum l
    lengthPlusWc l = if head l == 0 then length l else length l + wildcardCnt
    wildcardCnt = length $ filter (\(a, b) -> a == 0 && b == 0) (zip as bs)

main = do
    n <- getInt
    as <- getInts
    bs <- getInts
    print $ process as bs

{-# LANGUAGE Safe #-}
{-# Options_GHC -O3 #-}
import Data.ByteString.Builder
import Data.Monoid
import System.IO
import qualified Data.ByteString.Char8 as C
import Data.Char
import Data.Array.Unboxed
import qualified Data.Sequence as S
import Data.Foldable
import Data.List
import Data.Ratio

ru, ri :: C.ByteString -> Int

ru = C.foldl' (\a c -> a * 10 - 48 + ord c) 0
ri s
  | C.head s == '-' = negate $ ru $ C.tail s
  | otherwise = ru s

test :: Int -> [Int] -> Int
test n l = r1 + r2
  where
    (a, l') = splitAt n l
    b = take n l'
    x = zip a b
    r2 = maximum $ (0 : ) $ map length $ group $ toList $ S.unstableSort $ S.fromList [j % i | (i, j) <- x, i /= 0]
    r1 = length $ filter (\(i, j) -> i == 0 && j == 0) x

main = do
  s <- C.getContents
  let (n:a) = map ri $ C.words s
  print $ test n a

{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ScopedTypeVariables #-}

module Main where

--import Debug.Trace

import Control.Monad
import Control.Monad.ST
import Control.DeepSeq
import Data.Function
import Data.Maybe
import Data.Either
import Data.Ord
import Data.Ratio
import qualified Data.Foldable as Foldable
import Data.Char
import Data.List
import Data.Array.IArray
import Data.Array.MArray.Safe
import qualified Data.Array.Unboxed as UA
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 read <$> getWords :: IO [Int]
getDoubles = map read <$> getWords :: 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 ()

---- Answer Code Section ----

divide a b
    | a == 0 && b /= 0 = Nothing
    | b == 0 = Just 0
    | otherwise = Just $ ((/) `on` (% 1)) a b

process :: [Int] -> [Int] -> Int
process as bs = if nonzeroD then maxDCnt + wildcardCnt else maxDCnt where
    ds = catMaybes $ zipWith divide as bs
    n = length ds
    dArr = listArray (1, n) (sort ds) :: Array Int (Ratio Int)
    dCnts = map snd $ scanl foldFn (1, (0, 0)) [1..n]
    foldFn (i, _) j = (i', (x, j - i' + 1)) where
        x = dArr ! j
        i' = until (\_i -> (dArr ! _i) == x) (+ 1) i
    maxDCnt = snd $ maximumBy (compare `on` snd) dCnts
    nonzeroD = length (filter (\(x, cnt) -> x /= (0%1) && cnt == maxDCnt) dCnts) > 0
    wildcardCnt = length $ filter (\(a, b) -> a == 0 && b == 0) (zip as bs)

main = do
    n <- getInt
    as <- getInts
    bs <- getInts
    print $ process as bs

{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ScopedTypeVariables #-}

module Main where

--import Debug.Trace

import Control.Monad
import Control.Monad.ST
import Control.DeepSeq
import Data.Function
import Data.Maybe
import Data.Either
import Data.Ord
import Data.Ratio
import qualified Data.Foldable as Foldable
import Data.Char
import Data.List
import Data.Array.IArray
import Data.Array.MArray.Safe
import qualified Data.Array.Unboxed as UA
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 read <$> getWords :: IO [Int]
getDoubles = map read <$> getWords :: 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 ()

---- Answer Code Section ----

divide a b
    | a == 0 && b /= 0 = Nothing
    | b == 0 = Just 0
    | otherwise = Just $ ((/) `on` (% 1)) a b

process :: [Int] -> [Int] -> Int
process as bs = maximum dCnts where
    ds = catMaybes $ zipWith divide as bs
    n = length ds
    dArr = listArray (1, n) (sort ds) :: Array Int (Ratio Int)
    dCnts = map snd $ scanl foldFn (1, 0) [1..n]
    foldFn (i, _) j = (i', j - i' + 1) where
        x = dArr ! j
        i' = until (\_i -> (dArr ! _i) == x) (+ 1) i

main = do
    n <- getInt
    as <- getInts
    bs <- getInts
    print $ process as bs

{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ScopedTypeVariables #-}

module Main where

--import Debug.Trace

import Control.Monad
import Control.Monad.ST
import Control.DeepSeq
import Data.Function
import Data.Maybe
import Data.Either
import Data.Ord
import Data.Ratio
import qualified Data.Foldable as Foldable
import Data.Char
import Data.List
import Data.Array.IArray
import Data.Array.MArray.Safe
import qualified Data.Array.Unboxed as UA
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 read <$> getWords :: IO [Int]
getDoubles = map read <$> getWords :: 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 ()

---- Answer Code Section ----

divide a b
    | a == 0 && b /= 0 = Nothing
    | b == 0 = Just 0
    | otherwise = Just $ ((/) `on` (% 1)) a b

process :: [Int] -> [Int] -> Int
process as bs = maximum dCnts where
    ds = catMaybes $ zipWith divide as bs
    n = length ds
    dArr = listArray (1, n) (sort ds) :: Array Int (Ratio Int)
    dCnts = map snd $ scanl foldFn (1, 0) [1..n]
    foldFn (i, _) j = (i', j - i' + 1 + extra) where
        extra = if x == 0 then 0 else wildcardCnt
        x = dArr ! j
        i' = until (\_i -> (dArr ! _i) == x) (+ 1) i
    wildcardCnt = length $ filter (\(a, b) -> a == 0 && b == 0) (zip as bs)

main = do
    n <- getInt
    as <- getInts
    bs <- getInts
    print $ process as bs