{-# LANGUAGE BangPatterns      #-}
{-# LANGUAGE OverloadedStrings #-}

import           Control.Applicative
import           Control.Monad
import qualified Data.ByteString.Char8 as B
import           Debug.Trace

import           Data.Sequence         (Seq (..), ViewL (..), ViewR (..), (<|),
                                        (><), (|>))
import qualified Data.Sequence         as S

readInt' :: B.ByteString -> Int
readInt' bs | Just (n, _) <- B.readInt bs = n

insert :: a -> Seq a -> Seq a
insert = (<|)

delete :: Eq a => a -> Seq a -> Seq a
delete x s =
    case S.viewl r of
        EmptyL -> s
        x :< xs -> l >< xs
  where
    (l, r) = S.breakl (== x) s

deleteFirst :: Seq a -> Seq a
deleteFirst s =
    case S.viewl s of
        x :< xs -> xs

deleteLast :: Seq a -> Seq a
deleteLast s =
    case S.viewr s of
        xs :> x -> xs

make :: [(B.ByteString, Int)] -> Seq Int
make xs = go S.empty xs
  where
    go !seq [] = seq
    go !seq ((com,n):cs)
        | com == "insert" = go (insert n seq) cs
        | com == "delete" = go (delete n seq) cs
        | com == "deleteFirst" = go (deleteFirst seq) cs
        | com == "deleteLast"  = go (deleteLast seq) cs

print' :: Seq Int -> IO ()
print' s =
    case S.viewl s of
        EmptyL -> putStrLn ""
        a :< s' -> putStr (show a) >> go s'
  where
    go s =
        case S.viewl s of
            EmptyL -> putStrLn ""
            a :< s' -> putStr (" " ++ show a) >> go s'

main :: IO ()
main = do
    B.getLine
    let f xs =
            case xs of
                [a]    -> (a, 0)
                [a, b] -> (a, readInt' b)
    xs <- fmap (f . B.words) . B.lines <$> B.getContents
    print' $ make xs


import Control.Applicative
import Control.Monad
import Data.List
main = do
    n <- getLine
    s <- map read . words <$> getLine
    q <- getLine
    t <- map read . words <$> getLine
    let s' = qsort s
    let a = foldl' (+) 0 [1 | x <- t, binarysearch s' x]
    print a

qsort :: (Ord a) => [a] -> [a]
qsort [] = []
qsort (x:xs) = small ++ [x] ++ large
    where   small = [s | s <- xs, x > s]
            large = [l | l <- xs, x < l]

binarysearch :: [Int] -> Int -> Bool
binarysearch [] _ = False
binarysearch [x] n = x == n
binarysearch xs n
        | n == p = True
        | n <  p = binarysearch (take (m-1) xs) n
        | otherwise = binarysearch (drop m xs) n
        where   m = (length xs) `div` 2
                p = xs !! (m-1)

Global OOD problem IDs are disjoint from train, validation, and in-distribution test problem IDs.

Search II

You are given a sequence of n integers S and a sequence of different q integers T. Write a program which outputs C, the number of integers in T which are also in the set S.

Input

In the first line n is given. In the second line, n integers are given. In the third line q is given. Then, in the fourth line, q integers are given.

Output

Print C in a line.

Constraints

Elements in S is sorted in ascending order

n ≤ 100000

q ≤ 50000

0 ≤ an element in S ≤ 109

0 ≤ an element in T ≤ 109

Sample Input 1

5
1 2 3 4 5
3
3 4 1

Sample Output 1

3

Sample Input 2

3
1 2 3
1
5

Sample Output 2

0

Sample Input 3

5
1 1 2 2 3
2
1 2

Sample Output 3

2

Notes

Submitted source-code file size, in bytes.

Execution CPU time reported by official Project CodeNet metadata, in milliseconds.

Peak memory usage reported by official Project CodeNet metadata, in kilobytes.


import Control.Applicative ((<$>), (<*>))
import Data.ByteString.Char8 (ByteString)
import qualified Data.ByteString.Char8 as B
import Data.List (unfoldr, foldl')
import Data.Char (isSpace)
import Data.Vector (Vector, (!))
import qualified Data.Vector as V

main :: IO ()
main = do
  solve <$> readLn <*> f <*> (B.getLine >> f) >>= print
  where f = readiv B.readInt <$> B.getLine

solve :: Int -> Vector Int -> Vector Int -> Int
solve n ss ts = V.foldl' f 0 ts
  where f ct x | bsearch (flip compare x . (ss !)) 0 n = ct + 1
               | otherwise = ct

bsearch :: (Int -> Ordering) -> Int -> Int -> Bool
bsearch f l r | l >= r = False
              | otherwise = case f m of
                             GT -> bsearch f l m
                             LT -> bsearch f (m+1) r
                             EQ -> True
  where
    m = (l + r) `div` 2

readiv :: Integral a =>  (ByteString -> Maybe (a, ByteString)) -> ByteString -> Vector a
readiv f = V.unfoldr g
  where
    g s = do
      (n, s') <- f s
      return (n, B.dropWhile isSpace s')


main :: IO ()
main = do
    [n, k] <- fmap (map read . words) getLine     :: IO [Int]
    ws     <- fmap (map read . lines) getContents :: IO [Int]
    let sumW = sum ws
        minP = sumW `div` k - 1
        maxP = sumW
    print $ solve n k ws minP maxP

solve :: Int -> Int -> [Int] -> Int -> Int -> Int
solve n k ws minP maxP = mlc minP maxP
  where
    mlc row high
        | (high - row) == 1 = high
        | c < n             = mlc mid high
        | otherwise         = mlc row mid
      where
        c   = lc ws mid 1 0 0
        mid = (high + row) `div` 2

    lc []     p track loaded total = total
    lc (x:xs) p track loaded total
        | total == n = total
        | track > k  = total
        | otherwise  =
            if (loaded + x) > p then
                lc (x:xs) p (track + 1) 0 total
            else
                lc xs p track (loaded + x) (total + 1)

MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

You are given $n$ packages of $w_i$ kg from a belt conveyor in order ($i = 0, 1, ... n-1$). You should load all packages onto $k$ trucks which have the common maximum load $P$. Each truck can load consecutive packages (more than or equals to zero) from the belt conveyor unless the total weights of the packages in the sequence does not exceed the maximum load $P$.

Write a program which reads $n$, $k$ and $w_i$, and reports the minimum value of the maximum load $P$ to load all packages from the belt conveyor.

Input

In the first line, two integers $n$ and $k$ are given separated by a space character. In the following $n$ lines, $w_i$ are given respectively.

Output

Print the minimum value of $P$ in a line.

Constraints

$1 \leq n \leq 100,000$

$1 \leq k \leq 100,000$

$1 \leq w_i \leq 10,000$

Sample Input 1

5 3
8
1
7
3
9

Sample Output 1

10

If the first truck loads two packages of $\{8, 1\}$, the second truck loads two packages of $\{7, 3\}$ and the third truck loads a package of $\{9\}$, then the minimum value of the maximum load $P$ shall be 10.

Sample Input 2

4 2
1
2
2
6

Sample Output 2

6

If the first truck loads three packages of $\{1, 2, 2\}$ and the second truck loads a package of $\{6\}$, then the minimum value of the maximum load $P$ shall be 6.


{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-missing-signatures #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-incomplete-patterns #-}
{-# OPTIONS_GHC -fno-warn-name-shadowing #-}
{-# LANGUAGE OverloadedStrings #-}
-- {-# LANGUAGE FlexibleContexts #-}
-- {-# LANGUAGE MultiWayIf #-}
-- {-# LANGUAGE BangPatterns #-}
-- {-# LANGUAGE ViewPatterns #-}
-- {-# LANGUAGE TupleSections #-}

import           System.IO hiding (char8)
import           Control.Applicative
import           Control.Monad
import           Data.List
import           Data.Tuple
import           Data.Int
import           Data.Char
import           Data.Function (on)
import           Data.Ord (comparing)
import           Data.Monoid (mappend)
import           Data.Array
-- import           Data.Array.Unboxed
-- import           Data.Array.IArray
-- import           Data.Array.ST
-- import           Data.Array.MArray
-- import           Data.Array.Unsafe
-- import           Data.Array.Base(unsafeRead, unsafeWrite)
-- import           Data.Array.IO
import           Data.Ix
import           Data.Maybe
-- import           Data.Monoid hiding ((<>))
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as BL
import           Data.ByteString.Builder
-- import           Data.Graph
-- import           Data.Vector.Unboxed ((//), (++), (!), (!?))
-- import qualified Data.Vector.Unboxed as U
-- import           Data.IntSet (IntSet)
-- import qualified Data.IntSet as IntSet
-- import           Data.IntMap.Strict (IntMap)
-- import qualified Data.IntMap.Strict as IntMap
-- import           Data.Sequence ((|>), (<|), (><),ViewR(..), ViewL(..), Seq)
-- import qualified Data.Sequence              as Seq
-- import           Data.Foldable (toList, minimumBy)
-- import           Debug.Trace

main = solve 0 <$ getInt1 <*> getInts >>= \(a,b) -> putIntN b >> print a

solve :: Int -> [Int] -> (Int, [Int])
solve c xs
  | length xs > 1 = merge (solve (c+1) ls) (solve (c+1) rs)
  | otherwise = (c, xs)
  where
    (ls, rs) = splitAt (length xs `div` 2) xs

merge :: (Int, [Int]) -> (Int, [Int]) -> (Int, [Int])
merge (c, []) (d, xs) = (c+d, xs)
merge (c, xs) (d, []) = (c+d, xs)
merge (c, x:xs) (d, y:ys)
  | x < y = conssnd x $ merge (c, xs) (d, y:ys)
  | otherwise = conssnd y $ merge (c, x:xs) (d, ys)

conssnd x (a, b) = (a, x:b)

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

getInt1 :: IO Int
getInt1 = readInt1 <$> BS.getLine

getInt2 :: IO (Int, Int)
getInt2 = readInt2 <$> BS.getLine

getInt3 :: IO (Int, Int, Int)
getInt3 = readInt3 <$> BS.getLine

getInts :: IO [Int]
getInts = readIntN <$> BS.getLine

getIntN :: Int -> IO [Int]
getIntN n = map readInt1 <$> replicateM n BS.getLine

format :: Show a => Maybe a -> IO ()
format Nothing = putStrLn "NO"
format (Just a) = putStrLn "YES" >> print a

-- [1,2,3] -> 1 2 3
putIntN :: [Int] -> IO ()
putIntN [] = return ()
putIntN xs = BL.putStrLn . toLazyByteString . foldl1 mappend . intersperse (char8 ' ') $ map intDec xs

readInt1 :: BS.ByteString -> Int
readInt1 = fst . fromJust . BS.readInt

readInt2 :: BS.ByteString -> (Int,Int)
readInt2 = toTuple . readIntN

readInt3 :: BS.ByteString -> (Int,Int,Int)
readInt3 = toTriple . readIntN

readIntN :: BS.ByteString -> [Int]
readIntN =  map readInt1 . BS.words

readInt641 :: BS.ByteString -> Int64
readInt641 = fromIntegral . fst . fromJust . BS.readInteger

readInt642 :: BS.ByteString -> (Int64,Int64)
readInt642 = toTuple . readInt64N

readInt643 :: BS.ByteString -> (Int64,Int64,Int64)
readInt643 = toTriple . readInt64N

readInt64N :: BS.ByteString -> [Int64]
readInt64N =  map readInt641 . BS.words

readInteger1 :: BS.ByteString -> Integer
readInteger1 = fst . fromJust . BS.readInteger

readInteger2 :: BS.ByteString -> (Integer,Integer)
readInteger2 = toTuple . readIntegerN

readInteger3 :: BS.ByteString -> (Integer,Integer,Integer)
readInteger3 = toTriple . readIntegerN

readIntegerN :: BS.ByteString -> [Integer]
readIntegerN =  map readInteger1 . BS.words

toTuple :: [a] -> (a, a)
toTuple [x, y] = (x, y)

toTriple :: [a] -> (a, a, a)
toTriple [x, y, z] =(x, y, z)

fromTuple :: (a, a) -> [a]
fromTuple (x, y) = [x, y]

fromTriple :: (a, a, a) -> [a]
fromTriple (x, y, z) = [x, y, z]

-- if not applying, use "const"

applyTuple :: (a -> a') -> (b -> b') -> (a, b) -> (a', b')
applyTuple f g (x, y) = (f x, g y)

applyTriple :: (a -> a') -> (b -> b') -> (c -> c') -> (a, b, c) -> (a', b', c')
applyTriple f g h (x, y, z) = (f x, g y, h z)

-- @since 4.8.0.0
sortOn' :: Ord b => (a -> b) -> [a] -> [a]
sortOn' f =
  map snd . sortBy (comparing fst) . map (\x -> let y = f x in y `seq` (y, x))

Merge Sort

Write a program of a Merge Sort algorithm implemented by the following pseudocode. You should also report the number of comparisons in the Merge function.

Merge(A, left, mid, right)
n1 = mid - left;
n2 = right - mid;
create array L[0...n1], R[0...n2]
for i = 0 to n1-1
do L[i] = A[left + i]
for i = 0 to n2-1
do R[i] = A[mid + i]
L[n1] = SENTINEL
R[n2] = SENTINEL
i = 0;
j = 0;
for k = left to right-1
if L[i] <= R[j]
then A[k] = L[i]
i = i + 1
else A[k] = R[j]
j = j + 1

Merge-Sort(A, left, right){
if left+1 < right
then mid = (left + right)/2;
call Merge-Sort(A, left, mid)
call Merge-Sort(A, mid, right)
call Merge(A, left, mid, right)

Input

In the first line n is given. In the second line, n integers are given.

Output

In the first line, print the sequence S. Two consequtive elements should be separated by a space character.

In the second line, print the number of comparisons.

Constraints

n ≤ 500000

0 ≤ an element in S ≤ 109

Sample Input 1

10
8 5 9 2 6 3 7 1 10 4

Sample Output 1

1 2 3 4 5 6 7 8 9 10
34

Notes


main :: IO()
main = do
  n <- readLn :: IO Int
  let
    left = (0, 0)
    right = (100, 0)
  outputPoint left
  koch n left right
  outputPoint right

koch :: Int -> (Float, Float) -> (Float, Float) -> IO()
koch 0 _ _ = return ()
koch n left@(x1, y1) right@(x2, y2) = do
  let
    s = ((2 * x1 + x2) / 3, (2 * y1 + y2) / 3)
    t = ((x1 + 2 * x2) / 3, (y1 + 2 * y2) / 3)
    u =
      (
        (fst t - fst s) * (cos $ pi / 3) - (snd t - snd s) * (sin $ pi / 3) + fst s,
        (fst t - fst s) * (sin $ pi / 3) + (snd t - snd s) * (cos $ pi / 3) + snd s
      )
  koch (n - 1) left s
  outputPoint s
  koch (n - 1) s u
  outputPoint u
  koch (n - 1) u t
  outputPoint t
  koch (n - 1) t right

outputPoint :: (Float, Float) -> IO()
outputPoint (x, y) = putStrLn $ (show x) ++ " " ++ (show y)

Koch Curve

Write a program which reads an integer n and draws a Koch curve based on recursive calles of depth n.

The Koch curve is well known as a kind of fractals.

You can draw a Koch curve in the following algorithm:

Divide a given segment (p1, p2) into three equal segments.

Replace the middle segment by the two sides of an equilateral triangle (s, u, t) of the same length as the segment.

Repeat this procedure recursively for new segments (p1, s), (s, u), (u, t), (t, p2).

You should start (0, 0), (100, 0) as the first segment.

Input

An integer n is given.

Output

Print each point (x, y) of the Koch curve. Print a point in a line. You should start the point(0, 0), which is the endpoint of the first segment and end with the point (100, 0), the other endpoint so that you can draw the Koch curve as an unbroken line. Each solution should be given as a decimal with an arbitrary number of fractional digits, and with an absolute error of at most 10-4.

Constraints

0 ≤ n ≤ 6

Sample Input 1

1

Sample Output 1

0.00000000 0.00000000
33.33333333 0.00000000
50.00000000 28.86751346
66.66666667 0.00000000
100.00000000 0.00000000

Sample Input 2

2

Sample Output 2

0.00000000 0.00000000
11.11111111 0.00000000
16.66666667 9.62250449
22.22222222 0.00000000
33.33333333 0.00000000
38.88888889 9.62250449
33.33333333 19.24500897
44.44444444 19.24500897
50.00000000 28.86751346
55.55555556 19.24500897
66.66666667 19.24500897
61.11111111 9.62250449
66.66666667 0.00000000
77.77777778 0.00000000
83.33333333 9.62250449
88.88888889 0.00000000
100.00000000 0.00000000

Notes


import Control.Applicative
import Control.Monad
import Data.Word
import Data.Array.IO

main = do
        n <- readLn
        list <- map read.words<$>getLine
        arr <- newListArray (1,n) list
        b <- countingSort 10000 arr
        putStrLn.unwords.map show =<< getElems b

countingSort :: Word32 -> IOUArray Word32 Word32 -> IO (IOUArray Word32 Word32)
countingSort k arr = do
        countArr <- newArray (0,k) 0 :: IO (IOUArray Word32 Word32)
        countFreq countArr arr
        accumulateCount countArr
        writeElems countArr arr
        where
            countFreq :: IOUArray Word32 Word32 -> IOUArray Word32 Word32 -> IO ()
            countFreq ca a = do
                (s,g) <- getBounds a
                forM_ [s..g] $ \j -> readArray a j >>= \i -> modifyArray ca i (+1)
            accumulateCount ca = forM_ [1..k] $ \i -> do
                e' <- readArray ca (i-1)
                modifyArray ca i (+e')
            writeElems :: IOUArray Word32 Word32 -> IOUArray Word32 Word32 -> IO (IOUArray Word32 Word32)
            writeElems ca a = do
                (s,g) <- getBounds a
                b <- newArray_ (s,g)
                forM_ [g,(g-1)..1] $ \j -> do
                    eA <- readArray a j
                    eC <- readArray ca eA
                    writeArray b eC eA
                    modifyArray ca eA (subtract 1)
                return b

modifyArray arr i f = do
        e <- readArray arr i
        writeArray arr i (f e)

Counting Sort

Counting sort can be used for sorting elements in an array which each of the n input elements is an integer in the range 0 to k. The idea of counting sort is to determine, for each input element x, the number of elements less than x as C[x]. This information can be used to place element x directly into its position in the output array B. This scheme must be modified to handle the situation in which several elements have the same value. Please see the following pseudocode for the detail:

Counting-Sort(A, B, k)
1 for i = 0 to k
2 do C[i] = 0
3 for j = 1 to length[A]
4 do C[A[j]] = C[A[j]]+1
5 /* C[i] now contains the number of elements equal to i */
6 for i = 1 to k
7 do C[i] = C[i] + C[i-1]
8 /* C[i] now contains the number of elements less than or equal to i */
9 for j = length[A] downto 1
10 do B[C[A[j]]] = A[j]
11 C[A[j]] = C[A[j]]-1

Write a program which sorts elements of given array ascending order based on the counting sort.

Input

The first line of the input includes an integer n, the number of elements in the sequence.

In the second line, n elements of the sequence are given separated by spaces characters.

Output

Print the sorted sequence. Two contiguous elements of the sequence should be separated by a space character.

Constraints

1 ≤ n ≤ 2,000,000

0 ≤ A[i] ≤ 10,000

Sample Input 1

7
2 5 1 3 2 3 0

Sample Output 1

0 1 2 2 3 3 5


import Control.Monad.Reader
import Data.Array.IArray

main = do
    [n,m] <- fmap (map read.words) getLine
    cs <- fmap (map read.words) getLine
    let coins = array (1,m) $ zip [1..] cs
    print $ runReader (minCoinsR m n) coins

minCoinsR :: Int -> Int -> Reader (Array Int Int) Int
minCoinsR i j
  | j < 0 = return (maxBound - 1)
  | j == 0 = return 0
  | i == 1 = return j
  | otherwise = do
       arr <- ask
       l <- minCoinsR (i-1) j
       r <- minCoinsR i (j-arr!i)
       return $ min l (r+1)

Coin Changing Problem

Find the minimum number of coins to make change for n cents using coins of denominations d1, d2,.., dm. The coins can be used any number of times.

Input

n m
d1 d2 ... dm

Two integers n and m are given in the first line. The available denominations are given in the second line.

Output

Print the minimum number of coins in a line.

Constraints

1 ≤ n ≤ 50000

1 ≤ m ≤ 20

1 ≤ denomination ≤ 10000

The denominations are all different and contain 1.

Sample Input 1

55 4
1 5 10 50

Sample Output 1

2

Sample Input 2

15 6
1 2 7 8 12 50

Sample Output 2

2

Sample Input 3

65 6
1 2 7 8 12 50

Sample Output 3

3


{-# OPTIONS_GHC -O2 #-}
import Control.Applicative
import Data.Array
import Data.List (foldl')
import Data.Foldable (maximumBy)
import Data.Ord (comparing)
import qualified Data.Set as Set

main = do
  len <- (read :: String -> Int) <$> getLine
  xs <- map (read :: String -> Int) . lines <$> getContents
  let arr = listArray (1,len) xs
  print $ snd $ maximumBy (comparing snd) $ syorinaiyou arr len

syorinaiyou arr len =
  foldl' (keisan arr) Set.empty (reverse [1..len])
    where
      keisan arr set n
        | Set.null set =  Set.insert ((arr ! n),1) set
        | otherwise  = seisa arr set n
        where
          seisa arr set n
            | Set.null set' = Set.insert (hikaku_moto,1) set
            | otherwise  = Set.insert (hikaku_moto, oldLIS + 1) set
            where
              hikaku_moto = arr ! n
              set'   = snd $ Set.split (hikaku_moto + 1 , 0) set
              oldLIS = snd $ maximumBy (comparing snd) set'

Longest Increasing Subsequence

For a given sequence A = {a0, a1, ... , an-1}, find the length of the longest increasing subsequnece (LIS) in A.

An increasing subsequence of A is defined by a subsequence {ai0, ai1, ... , aik} where 0 ≤ i0 < i1 < ... < ik < n and ai0 < ai1 < ... < aik.

Input

n
a0
a1
:
an-1

In the first line, an integer n is given. In the next n lines, elements of A are given.

Output

The length of the longest increasing subsequence of A.

Constraints

1 ≤ n ≤ 100000

0 ≤ ai ≤ 109

Sample Input 1

5
5
1
3
2
4

Sample Output 1

3

Sample Input 2

3
1
1
1

Sample Output 2

1


import Data.Array.IO

type Value = Int
type Weight = Int
type Item = (Weight, Value)
type ItemList = [Item]
type Capacity = Int

main :: IO ()
main = do
  input <- getContents
  let nums = map ((\x -> (last x, head x)) . map (read :: String -> Int) . words) . lines $ input
      capacity = fst . head $ nums
      items = tail nums
  memo <- newArray ((0, 0), (capacity, length items)) (0 - 1) :: IO (IOUArray (Int, Int) Int)
  dp (capacity, items) memo
  putStrLn . show . last =<< getElems memo

memoize :: (Capacity, ItemList) -> IOUArray (Int, Int) Int -> IO Int
memoize (c, i) t = do
  v <- readArray t (c, length i)
  if v < 0
    then do
      dp (c, i) t
      return =<< readArray t (c, length i)
    else return v

dp :: (Capacity, ItemList) -> IOUArray (Int, Int) Int -> IO (IOUArray (Int, Int) Int)
dp (c, []) t = do
  writeArray t (c, 0) 0
  return t
dp (c, as@(i:is)) t
  | c < fst i = do
    v <- memoize (c, is) t
    writeArray t (c, length as) v
    return t
  | otherwise = do
    x <- memoize (c, is) t
    y <- memoize (c - fst i, is) t
    writeArray t (c, length as) (max x $ y + snd i)
    return t

0-1 Knapsack Problem II

You have N items that you want to put them into a knapsack. Item i has value vi and weight wi.

You want to find a subset of items to put such that:

The total value of the items is as large as possible.

The items have combined weight at most W, that is capacity of the knapsack.

Find the maximum total value of items in the knapsack.

Input

N W
v1 w1
v2 w2
:
vN wN

The first line consists of the integers N and W. In the following N lines, the value and weight of the i-th item are given.

Output

Print the maximum total values of the items in a line.

Constraints

1 ≤ N ≤ 100

1 ≤ vi ≤ 100

1 ≤ wi ≤ 10,000,000

1 ≤ W ≤ 1,000,000,000

Sample Input 1

4 5
4 2
5 2
2 1
8 3

Sample Output 1

13

Sample Input 2

2 20
5 9
4 10

Sample Output 2

9


{-# OPTIONS_GHC -O2 #-}
import Control.Applicative
import Data.IORef
import qualified Data.Vector.Unboxed.Mutable as VM
import qualified Data.Vector.Unboxed as V
import Control.Monad

main = do
  [_,capa] <- map (read :: String -> Int) . words <$> getLine
  goods' <- map (map (read :: String -> Int) . words) . lines <$> getContents
  let goods = bunkai goods' []
  capaVM <- VM.replicate (capa+1) 0
  ans <- newIORef 0
  mapM_ (resolve capa capaVM ans) goods
  print =<< readIORef ans

bunkai ([x,y,n]:xs) ys
  | null xs = merge [x,y] n ys
  | otherwise = bunkai xs (merge [x,y] n ys)
  where
    merge xs n ys
      | n == 1 = xs:ys
      | otherwise = merge xs (n-1) (xs:ys)

resolve capa capaVM ans [v,w] =
  if capa < w
    then return ()
    else V.mapM_ (koushin [v,w]) (V.enumFromStepN (capa-w) (-1) (capa-w+1))
       where
         koushin [v,w] n = do
           oldValue <- VM.read capaVM n
           newValue <- VM.read capaVM (n+w)
           judge oldValue newValue
             where
               judge oldValue newValue
                 | n == 0 && newValue <= v  = kakikae
                 | n ==0                    = return ()
                 | newValue >= v + oldValue = return ()
                 | otherwise  = kakikae
                 where
                   kakikae = do
                     VM.write capaVM (n+w) (v + oldValue)
                     ans' <- readIORef ans
                     writeIORef ans (max ans' (v + oldValue))

Knapsack Problem with Limitations

You have N items that you want to put them into a knapsack. Item i has value vi, weight wi and limitation mi.

You want to find a subset of items to put such that:

The total value of the items is as large as possible.

The items have combined weight at most W, that is capacity of the knapsack.

You can select at most mi items for ith item.

Find the maximum total value of items in the knapsack.

Input

N W
v1 w1 m1
v2 w2 m2
:
vN wN mN

The first line consists of the integers N and W. In the following N lines, the value, weight and limitation of the i-th item are given.

Output

Print the maximum total values of the items in a line.

Constraints

1 ≤ N ≤ 100

1 ≤ vi ≤ 1,000

1 ≤ wi ≤ 1,000

1 ≤ mi ≤ 10,000

1 ≤ W ≤ 10,000

Sample Input 1

4 8
4 3 2
2 1 1
1 2 4
3 2 2

Sample Output 1

12

Sample Input 2

2 100
1 1 100
2 1 50

Sample Output 2

150


{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}
{-# LANGUAGE BangPatterns #-}
module Main (main) where
import Data.Int (Int32)
import Data.Ix
import Control.Monad
import Control.Applicative
import Data.Monoid
import Data.Maybe (fromJust)
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as B8
newtype Min = Min {fromMin :: Int32 } deriving (Ord,Show,Eq,Read)
instance Monoid Min where
  mempty = Min maxBound
  mappend = min

newtype Max = Max Int deriving (Ord,Show,Eq)
instance Monoid Max where
  mempty = Max minBound
  mappend = max

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

main :: IO ()
main = do
  n:q:_ <- getInts
  let bst = fromList $ replicate n mempty :: STree Min
  queries <- replicateM q $ getInts
  go bst queries
  return ()
  where
    go _ [] = return ()
    go tree ((q:x:y:_):queries)
      -- | traceShow tree False = undefined
      | q == 0 = do -- update
          let tree' = update tree x (Min $ fromIntegral y)
          go tree' queries
      | otherwise = do -- find
          print . fromMin $ query tree (x, y)
          go tree queries
    go _ _ = error "undefined pattern match"

type Range = (Int,Int)
data STree v = Leaf {-# UNPACK #-}!Int !v
             | Branch {-# UNPACK #-}!Range !v !(STree v) !(STree v)
             deriving Show

range :: STree v-> Range
range !(Leaf r _) = (r,r)
range !(Branch r _ _ _) = r
{-# INLINE range #-}

val :: STree v -> v
val !(Leaf _ v) = v
val !(Branch _ v _ _) = v
{-# INLINE val #-}

left,right :: STree v -> Int
left = fst . Main.range
right = snd . Main.range
{-#INLINE left  #-}
{-#INLINE right #-}

fromList :: Monoid v => [v] -> STree v
fromList !xs = makeTree 0 (length xs) xs
{-# INLINE fromList #-}

makeTree :: Monoid v => Int -> Int -> [v] -> STree v
makeTree !l !r !es = loop $ map (uncurry f) (zip [l..r] es)
  where
    loop ![x] = x
    loop !xs = loop $ buildTree xs
    f :: Int -> v -> STree v
    f !ix !v = Leaf ix v
    buildTree !(a:b:ys) = let v = val a `mappend` val b
                          in Branch (left a,right b) v a b : buildTree ys
    buildTree !x = x
{-# SPECIALIZE INLINE makeTree :: Int -> Int -> [Min] -> STree Min #-}

query :: Monoid v => STree v -> (Int, Int) -> v
query !t shape = loop t
  where
    loop (Leaf ix v)
      = if shape `inRange` ix then v else mempty
    loop (Branch (leftist,rightist) v lt rt)
      | shape `inRange` leftist
        && shape `inRange` rightist = v
      | otherwise = loop lt `mappend` loop rt
{-# SPECIALIZE INLINE query :: STree Min -> (Int,Int) -> Min #-}

update :: Monoid v => STree v -> Int -> v -> STree v
update !tree !ix !v = case tree of
  Leaf i _ -> if ix == i
              then Leaf i v
              else tree
  Branch rng _ l r
    | Main.range l `inRange` ix
      -> let l' = update l ix v
         in Branch rng (val l' `mappend` val r) l' r
    | otherwise
      -> let r' = update r ix v
         in Branch rng (val l `mappend` val r') l r'
{-# SPECIALIZE INLINE
    update :: STree Min -> Int -> Min -> STree Min #-}
{-# SPECIALIZE INLINE
    update :: STree Max -> Int -> Max -> STree Max #-}
{-# SPECIALIZE INLINE
    update :: Num a => STree (Sum a)-> Int -> Sum a -> STree (Sum a) #-}
{-# SPECIALIZE INLINE
    update :: Num a => STree (Product a)-> Int -> Product a -> STree (Product a) #-}

Range Minimum Query (RMQ)

Write a program which manipulates a sequence A = {a0, a1, . . . , an-1} with the following operations:

find(s, t): report the minimum element in as, as+1, . . . ,at.

update(i, x): change ai to x.

Note that the initial values of ai (i = 0, 1, . . . , n−1) are 231-1.

Input

n q
com0 x0 y0
com1 x1 y1
...
comq−1 xq−1 yq−1

In the first line, n (the number of elements in A) and q (the number of queries) are given. Then, q queries are given where com represents the type of queries. '0' denotes update(xi, yi) and '1' denotes find(xi, yi).

Output

For each find operation, print the minimum element.

Constraints

1 ≤ n ≤ 100000

1 ≤ q ≤ 100000

If comi is 0, then 0 ≤ xi < n, 0 ≤ yi < 231-1.

If comi is 1, then 0 ≤ xi < n, 0 ≤ yi < n.

Sample Input 1

3 5
0 0 1
0 1 2
0 2 3
1 0 2
1 1 2

Sample Output 1

1
2

Sample Input 2

1 3
1 0 0
0 0 5
1 0 0

Sample Output 2

2147483647
5


{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE UnboxedTuples #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE MultiWayIf #-}

import Control.Monad
import Control.Monad.ST
import Control.Monad.State
import Control.Applicative
import Control.Arrow
import Control.Monad.Primitive
import Data.List
import Data.Array
import Data.Array.IO
import Data.Maybe
import Data.Bits
import Data.Ord
import Data.Ratio
import Data.Int
import Data.Char
import qualified Data.ByteString.Char8 as BS
import qualified Data.Set as Set
import qualified Data.Vector as V
import qualified Data.Vector.Mutable as VM
import qualified Data.Vector.Unboxed as VU
import qualified Data.Vector.Unboxed.Mutable as VUM
import qualified Data.Vector.Generic as VG
import qualified Data.Vector.Generic.Mutable as VGM
import Data.Tuple
import Data.Function
import Text.Printf
import Debug.Trace
import Numeric

modifyArray arr i f = readArray arr i >>= \x -> writeArray arr i (f x)

listToTuple2 [a,b] = (a,b)
listToTuple3 [a,b,c] = (a,b,c)
listToTuple4 [a,b,c,d] = (a,b,c,d)
listToTuple5 [a,b,c,d,e] = (a,b,c,d,e)

readIntBS = fst . fromJust . BS.readInt

for = flip map

infixr 1 ?
(?) :: Bool -> (a,a) -> a
(?) b t = (if b then fst else snd) t

main :: IO ()
main = do
  [n,q] <- map read . words <$> getLine :: IO [Int]
  queries <- replicateM q $ map readIntBS . BS.words <$> BS.getLine :: IO [[Int]]
  let
    inf = 2^31-1
    f x y = if x == inf then y else x
    test x = if x == inf then "INF" else show x

  seg <- newRangeSegmentTree n inf min inf f const :: IO (IOURangeSegmentTree Int)

  forM_ queries $ \query -> do
    case query of
      [0,s,t,x] -> modifyRangeSegmentTree seg s (t+1) (const x)
      [1,s,t] -> print =<< findRangeSegmentTree seg s (t+1)

    --mapM_ print =<< map (map (\(a,b) -> (test a, test b))) <$> showRangeSegmentTree seg
    --print ""

{-- 範囲更新・範囲取得のセグメント木--}
type MRangeSegmentTree v s a = ((v s a, a, (a -> a -> a)), (v s a, a, (a -> a -> a)), (a -> Int -> a))
-- 範囲取得用の(セグメント木,単位元,二項演算)、範囲更新用の(遅延セグメント木,単位元,二項演算)、
type STRangeSegmentTree s a = MRangeSegmentTree VM.MVector s a
type IORangeSegmentTree a = STRangeSegmentTree RealWorld a
type STURangeSegmentTree s a = MRangeSegmentTree VUM.MVector s a
type IOURangeSegmentTree a = STURangeSegmentTree RealWorld a

newRangeSegmentTree :: (PrimMonad m, VGM.MVector v a) => Int -> a -> (a -> a -> a) -> a -> (a -> a -> a) -> (a -> Int -> a) -> m (MRangeSegmentTree v (PrimState m) a)
newRangeSegmentTree n e1 f1 e2 f2 h = do
  tree1 <- VGM.replicate m e1
  tree2 <- VGM.replicate m e2
  return ((tree1,e1,f1),(tree2,e2,f2), h)
  where m = 2 * (2 ^ (ceiling $ logBase 2 (fromIntegral n))) - 1

modifyRangeSegmentTree :: (Eq a, PrimMonad m, VGM.MVector v a) => MRangeSegmentTree v (PrimState m) a -> Int -> Int -> (a -> a) -> m ()
modifyRangeSegmentTree ((tree1,e1,f1),(tree2,e2,f2),h) x y g = do
  aux 0 0 n >> return ()
  where
    n = (VGM.length tree1) `div` 2 + 1
    aux i l r = do
      propag i (r-l)
      if
        | r <= x || y <= l -> VGM.read tree1 i
        | x <= l && r <= y -> VGM.read tree2 i >>= \a -> VGM.write tree2 i (g a) >> return (g a)
        | otherwise -> aux (i*2+1) l ((l+r)`div`2) >>= \a -> aux (i*2+2) ((l+r)`div`2) r >>= \b -> VGM.write tree1 i (f1 a b) >> return (f1 a b)
    propag i len = do
      a <- VGM.read tree2 i
      when (a /= e2) $ do
        when (i<n-1) $ do
          VGM.read tree2 (i*2+1) >>= \b -> VGM.write tree2 (i*2+1) (f2 a b)
          VGM.read tree2 (i*2+2) >>= \b -> VGM.write tree2 (i*2+2) (f2 a b)
        VGM.read tree1 i >>= \a -> VGM.read tree2 i >>= \b -> VGM.write tree1 i (f2 (h b len) a)
        VGM.write tree2 i e2

findRangeSegmentTree :: (Eq a, PrimMonad m, VGM.MVector v a) => MRangeSegmentTree v (PrimState m) a -> Int -> Int -> m a
findRangeSegmentTree ((tree1,e1,f1),(tree2,e2,f2),h) x y = do
  aux 0 0 n
  where
    n = (VGM.length tree1) `div` 2 + 1
    aux i l r = do
      propag i (r-l)
      if
        | r <= x || y <= l -> return e1
        | x <= l && r <= y -> VGM.read tree1 i
        | otherwise -> aux (i*2+1) l ((l+r)`div`2) >>= \a -> aux (i*2+2) ((l+r)`div`2) r >>= \b -> return (f1 a b)
    propag i len = do
      a <- VGM.read tree2 i
      when (a /= e2) $ do
        when (i<n-1) $ do
          VGM.read tree2 (i*2+1) >>= \b -> VGM.write tree2 (i*2+1) (f2 a b)
          VGM.read tree2 (i*2+2) >>= \b -> VGM.write tree2 (i*2+2) (f2 a b)
        VGM.read tree1 i >>= \a -> VGM.read tree2 i >>= \b -> VGM.write tree1 i (f2 (h b len) a)
        VGM.write tree2 i e2

showRangeSegmentTree :: (PrimMonad m, VGM.MVector v a, Show a) => MRangeSegmentTree v (PrimState m) a -> m [[(a,a)]]
showRangeSegmentTree ((tree1,_,_),(tree2,_,_),_) = do
  let
    n = (VGM.length tree1) `div` 2 + 1
    xs = init $ scanl (+) 0 (takeWhile (<=n) (iterate (*2) 1))
    ys = reverse xs

  forM (zip xs ys) $ \(s,s') -> do
    forM [s..s*2] $ \i -> VGM.read tree1 i >>= \a -> VGM.read tree2 i >>= \b -> return (a,b)

RMQ and RUQ

Write a program which manipulates a sequence A = {a0, a1, . . . , an−1} with the following operations:

update(s, t, x): change as, as+1, ..., at to x.

find(s, t): report the minimum element in as, as+1, ..., at.

Note that the initial values of ai (i = 0, 1, . . . , n−1) are 231-1.

Input

n q
query1
query2
:
queryq

In the first line, n (the number of elements in A) and q (the number of queries) are given. Then, ith query queryi is given in the following format:

0 s t x

or

1 s t

The first digit represents the type of the query. '0' denotes update(s, t, x) and '1' denotes find(s, t).

Output

For each find operation, print the minimum value.

Constraints

1 ≤ n ≤ 100000

1 ≤ q ≤ 100000

0 ≤ s ≤ t < n

0 ≤ x < 231−1

Sample Input 1

3 5
0 0 1 1
0 1 2 3
0 2 2 2
1 0 2
1 1 2

Sample Output 1

1
2

Sample Input 2

1 3
1 0 0
0 0 0 5
1 0 0

Sample Output 2

2147483647
5


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

perm :: [Int] -> [a] -> [a]
perm y x = [ x!!i | i <- y ]
hRoll = [0,2,4,1,3,5]
toTop = [[0,1,2,3,4,5]
        ,[1,5,2,3,0,4]
        ,[2,1,5,0,4,3]
        ,[3,1,0,5,4,2]
        ,[4,0,2,3,5,1]
        ,[5,1,3,2,4,0]]
hRotate :: [a] -> [[a]]
hRotate d = [d, h d, (h.h) d, (h.h.h) d] where h = (perm hRoll)

allRotate :: [a] -> [[a]]
allRotate d = concat[ hRotate x | x <- map(\ x -> perm x d) toTop]

-- TSEWNB
main = do
    n <- readLn
    l <- replicateM n $ words <$> getLine
    let c = if foldr (&&) True [elemIndex (l!!x) (allRotate (l!!y)) == Nothing | x <- [0..n-2],y <- [x+1..n-1]]
              then "Yes" else "No"
    putStrLn $ c

MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Dice IV

Write a program which reads $n$ dices constructed in the same way as Dice I, and determines whether they are all different. For the determination, use the same way as Dice III.

Input

In the first line, the number of dices $n$ is given. In the following $n$ lines, six integers assigned to the dice faces are given respectively in the same way as Dice III.

Output

Print "Yes" if given dices are all different, otherwise "No" in a line.

Constraints

$2 \leq n \leq 100$

$0 \leq $ the integer assigned to a face $ \leq 100$

Sample Input 1

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

Sample Output 1

No

Sample Input 2

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

Sample Output 2

Yes


main = solve 1
    where solve n = do
            x <- readLn
            if (x == 0) then return ()
            else do
                putStrLn $ "Case " ++ show n ++ ": " ++ show x
                solve (n + 1)

Print Test Cases

In the online judge system, a judge file may include multiple datasets to check whether the submitted program outputs a correct answer for each test case. This task is to practice solving a problem with multiple datasets.

Write a program which reads an integer x and print it as is. Note that multiple datasets are given for this problem.

Input

The input consists of multiple datasets. Each dataset consists of an integer x in a line.

The input ends with an integer 0. You program should not process (print) for this terminal symbol.

Output

For each dataset, print x in the following format:

Case i: x

where i is the case number which starts with 1. Put a single space between "Case" and i. Also, put a single space between ':' and x.

Constraints

1 ≤ x ≤ 10000

The number of datasets ≤ 10000

Sample Input

3
5
11
7
8
19
0

Sample Output

Case 1: 3
Case 2: 5
Case 3: 11
Case 4: 7
Case 5: 8
Case 6: 19


module Main where

import Control.Applicative
import Text.Printf
import Numeric

main :: IO ()
main = do
  { _ <- getLine
  ; xs <- getInts
  ; let mx = maximum xs
  ; let mn = minimum xs
  ; let sm = sum xs
  ; putInts [mn, mx, sm]
  }

--

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

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

getDoubles :: IO [Double]
getDoubles = map read . words <$> getLine

putDoubles :: [Double] -> IO ()
putDoubles = putStrLn . unwords . map showDouble

showDouble :: Double -> String
showDouble x = showFFloat Nothing x ""

getStrings :: IO [String]
getStrings = words <$> getLine

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

MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Min, Max and Sum

Write a program which reads a sequence of $n$ integers $a_i (i = 1, 2, ... n)$, and prints the minimum value, maximum value and sum of the sequence.

Input

In the first line, an integer $n$ is given. In the next line, $n$ integers $a_i$ are given in a line.

Output

Print the minimum value, maximum value and sum in a line. Put a single space between the values.

Constraints

$0 < n \leq 10000$

$-1000000 \leq a_i \leq 1000000$

Sample Input

5
10 1 5 4 17

Sample Output

1 17 37


import Text.Printf
main = do
  hoge<-getLine
  str<-getLine
  let xs=map read $ words $ str::[Int]
  putStrLn $ (show$minimum xs)++" " ++(show$maximum xs)++" "++(show$sum xs)


main =
  let
    func = do
      line <- getLine
      let
        [h,w] = map read $ words line :: [Int]
        drawLine w =
          if w > 0
            then do
              putStr "#"
              drawLine (w-1)
            else do
              putStrLn ""
        drawRect h w =
          if h > 0
            then do
              drawLine w
              drawRect (h-1) w
            else do
              putStrLn ""
        in
          if h == 0 && w == 0
            then putStr ""
            else do
              drawRect h w
              func
    in func

Print a Rectangle

Draw a rectangle which has a height of H cm and a width of W cm. Draw a 1-cm square by single '#'.

Input

The input consists of multiple datasets. Each dataset consists of two integers H and W separated by a single space.

The input ends with two 0 (when both H and W are zero).

Output

For each dataset, print the rectangle made of H × W '#'.

Print a blank line after each dataset.

Constraints

1 ≤ H ≤ 300

1 ≤ W ≤ 300

Sample Input

3 4
5 6
2 2
0 0

Sample Output

####
####
####

######
######
######
######
######

##
##


solve [n,x] = length [0 | a<-[1..n], b<-[a+1..n], c<-[b+1..n], a+b+c == x]

main = getContents >>= mapM_ print . map solve . map (map read . words) . init . lines

How many ways?

Write a program which identifies the number of combinations of three integers which satisfy the following conditions:

You should select three distinct integers from 1 to n.

A total sum of the three integers is x.

For example, there are two combinations for n = 5 and x = 9.

1 + 3 + 5 = 9

2 + 3 + 4 = 9

Input

The input consists of multiple datasets. For each dataset, two integers n and x are given in a line.

The input ends with two zeros for n and x respectively. Your program should not process for these terminal symbols.

Constraints

3 ≤ n ≤ 100

0 ≤ x ≤ 300

Output

For each dataset, print the number of combinations in a line.

Sample Input

5 9
0 0

Sample Output

2

Note

      解説


import Control.Applicative

type Data = (Int, Int)

type Problem = [Data]

type Result = [Int]

count :: Data -> Int

count (n, x)
    = length $ filter (\(m, l, o) -> m + l + o == x) sets where
        sets = concat.concat $ [[[(m, l, o) | o <- [(l + 1)..n]] | l <- [(m + 1)..n]] | m <- [1..n]]

solve :: Problem -> Result

solve xs
    = map count xs

output :: Result -> String

output xs
    = concat $ map (\x -> show x ++ "\n") xs

input :: IO Problem

input
    = return =<< inputProblem []

inputProblem :: Problem -> IO Problem

inputProblem xs
    = do
        [n, x] <- map read.words <$> getLine
        if (n, x) /= (0, 0)
            then inputProblem $ xs ++ [(n, x)]
            else return xs

main :: IO ()

main
    = putStr.output =<< solve <$> input


module Main where

import Control.Applicative
import Numeric

main :: IO ()
main = loop

loop :: IO ()
loop = do
  { [n, x] <- getInts
  ; if n == 0 && x == 0 then return ()
    else print (length (filter ((x ==) . sum) (comb [1 .. n] 3))) >> loop
  }

comb :: [Int] -> Int -> [[Int]]
comb ns 0 = [[]]
comb ns k = if length ns == k then [ns]
            else map (head ns :) (comb (tail ns) (k - 1)) ++ comb (tail ns) k
--
getInts :: IO [Int]
getInts = map read . words <$> getLine

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

getDoubles :: IO [Double]
getDoubles = map read . words <$> getLine

putDoubles :: [Double] -> IO ()
putDoubles = putStrLn . unwords . map showDouble

showDouble :: Double -> String
showDouble d = showFFloat Nothing d ""


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

solve :: [[Int]] -> [String]
solve ([n,m,l]:matxs) =
    let (matA,matB) = splitAt n $ matxs in
    let mAB = [[sum $ zipWith (*) a b | b<-transpose matB] | a<-matA] in
    map (unwords . map show) mAB

main =
    mapM_ putStrLn =<< solve . takeInputs . lines <$> getContents
    where
    takeInputs :: [String] -> [[Int]]
    takeInputs = map (map read . words)

MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Matrix Multiplication

Write a program which reads a $n \times m$ matrix $A$ and a $m \times l$ matrix $B$, and prints their product, a $n \times l$ matrix $C$. An element of matrix $C$ is obtained by the following formula:

\[
c_{ij} = \sum_{k=1}^m a_{ik}b_{kj}
\]

where $a_{ij}$, $b_{ij}$ and $c_{ij}$ are elements of $A$, $B$ and $C$ respectively.

Input

In the first line, three integers $n$, $m$ and $l$ are given separated by space characters

In the following lines, the $n \times m$ matrix $A$ and the $m \times l$ matrix $B$ are given.

Output

Print elements of the $n \times l$ matrix $C$ ($c_{ij}$). Print a single space character between adjacent elements.

Constraints

$1 \leq n, m, l \leq 100$

$0 \leq a_{ij}, b_{ij} \leq 10000$

Sample Input

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

Sample Output

1 8 5
0 9 6
4 23 14

Note

      解説


import qualified Data.Text.Lazy as T
import qualified Data.Text.Lazy.IO as T
import qualified Data.Text.Lazy.Read as T
import Data.Bits

main :: IO ()
main = do
  let
    m = 300000 :: Int
  [n, k] <- map unsafeTextToInt . T.words <$> T.getLine :: IO [Int]
  let
    f :: [Int] -> Tree
    f = foldl step tree0
      where
        step :: Tree -> Int -> Tree
        step t x = modify (m + 1, t) x (y + 1)
          where
            y = query (m + 1, t) (max 0 (x - k), min m (x + k) + 1) :: Int
        tree0 = fromList . replicate (m + 1) $ 0 :: Tree
  as <- map unsafeTextToInt . T.lines <$> T.getContents :: IO [Int]
  print . extract . f $ as

data Tree = Node Int (Maybe Tree, Maybe Tree)

extract :: Tree -> Int
extract (Node x _) = x

unsafeLeft :: Tree -> Tree
unsafeLeft (Node _ (Just t, _)) = t

unsafeRight :: Tree -> Tree
unsafeRight (Node _ (_, Just t)) = t

singleton :: Int -> Tree
singleton = flip Node (Nothing, Nothing)

fromList :: [Int] -> Tree
fromList = unsafeLeft . head . rec . map singleton
  where
    rec :: [Tree] -> [Tree]
    rec (t : t' : ts) = rec (Node (extract t `max` extract t') (Just t, Just t') : rec ts)
    rec (t : _) = [Node (extract t) (Just t, Nothing)]
    rec _ = []

modify :: (Int, Tree) -> Int -> Int -> Tree
modify (1, Node x lr) _ d = Node (x `max` d) lr
modify (n, Node x (Just l, r)) i d | i < nl    = Node (x `max` d) (Just (modify (nl, l) i d), r)
  where
    nl = flip shiftR 1 . bit $ finiteBitSize n - countLeadingZeros n :: Int
modify (n, Node x (l, Just r)) i d = Node (x `max` d) (l, Just (modify (n - nl, r) (i - nl) d))
  where
    nl = flip shiftR 1 . bit $ finiteBitSize n - countLeadingZeros n :: Int

query :: (Int, Tree) -> (Int, Int) -> Int
query (n, t) (i, j) | i == 0 && n <= j = extract t
                    | j <= nl          = query (nl, unsafeLeft t) (i, j)
                    | nl <= i          = query (n - nl, unsafeRight t) (i - nl, j - nl)
                    | otherwise        = query (nl, unsafeLeft t) (i, nl) `max` query (n - nl, unsafeRight t) (nl, j - nl)
  where
    nl = flip shiftR 1 . bit $ finiteBitSize n - countLeadingZeros n :: Int

unsafeTextToInt :: T.Text -> Int
unsafeTextToInt s = case T.signed T.decimal s of
  Right (n, _) -> n
{-# INLINE unsafeTextToInt #-}

Score : 400 points

Problem Statement

You are given a sequence A_1, A_2, ..., A_N and an integer K.

Print the maximum possible length of a sequence B that satisfies the following conditions:

B is a (not necessarily continuous) subsequence of A.

For each pair of adjacents elements of B, the absolute difference of the elements is at most K.

Constraints

1 \leq N \leq 300,000

0 \leq A_i \leq 300,000

0 \leq K \leq 300,000

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K
A_1
A_2
:
A_N

Output

Print the answer.

Sample Input 1

10 3
1
5
4
3
8
6
9
7
2
4

Sample Output 1

7

For example, B = (1, 4, 3, 6, 9, 7, 4) satisfies the conditions.

It is a subsequence of A = (1, 5, 4, 3, 8, 6, 9, 7, 2, 4).

All of the absolute differences between two adjacent elements (|1-4|, |4-3|, |3-6|, |6-9|, |9-7|, |7-4|) are at most K = 3.


main = do
  li <- getLine
  let a:b:c:d:[] = map read $ words li :: [Integer]
  print $ foldl max (-1000000000001) [a * c, a * d, b * c, b * d]

Score : 200 points

Problem Statement

Given are integers a,b,c and d.
If x and y are integers and a \leq x \leq b and c\leq y \leq d hold, what is the maximum possible value of x \times y?

Constraints

-10^9 \leq a \leq b \leq 10^9

-10^9 \leq c \leq d \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

a b c d

Output

Print the answer.

Sample Input 1

1 2 1 1

Sample Output 1

2

If x = 1 and y = 1 then x \times y = 1.
If x = 2 and y = 1 then x \times y = 2.
Therefore, the answer is 2.

Sample Input 2

3 5 -4 -2

Sample Output 2

-6

The answer can be negative.

Sample Input 3

-1000000000 0 -1000000000 0

Sample Output 3

1000000000000000000


import qualified Data.Text.Lazy as T
import qualified Data.Text.Lazy.IO as T
import qualified Data.Text.Lazy.Read as T

main :: IO ()
main = do
  let
    modulus = 1000000007 :: Int
    modExp :: Integral a => Int -> a -> Int
    modExp = exp' 1
      where
        exp' z _ 0 = z
        exp' z w y = exp' z' w' y'
          where
            y' = y `div` 2
            w' = w * w `mod` modulus
            z' | even y    = z
               | otherwise = (z * w) `mod` modulus
  n <- unsafeTextToInt <$> T.getLine :: IO Int
  print $ (modExp 10 n - 2 * modExp 9 n + modExp 8 n) `mod` modulus

unsafeTextToInt :: T.Text -> Int
unsafeTextToInt s = case T.signed T.decimal s of
  Right (n, _) -> n
{-# INLINE unsafeTextToInt #-}

Score : 300 points

Problem Statement

How many integer sequences A_1,A_2,\ldots,A_N of length N satisfy all of the following conditions?

0 \leq A_i \leq 9

There exists some i such that A_i=0 holds.

There exists some i such that A_i=9 holds.

The answer can be very large, so output it modulo 10^9 + 7.

Constraints

1 \leq N \leq 10^6

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the answer modulo 10^9 + 7.

Sample Input 1

2

Sample Output 1

2

Two sequences \{0,9\} and \{9,0\} satisfy all conditions.

Sample Input 2

1

Sample Output 2

0

Sample Input 3

869121

Sample Output 3

2511445


{-# OPTIONS_GHC -O2 #-}
{-# LANGUAGE BangPatterns, BinaryLiterals, CPP, DerivingStrategies  #-}
{-# LANGUAGE DerivingVia, FlexibleContexts, FlexibleInstances       #-}
{-# LANGUAGE GeneralizedNewtypeDeriving, KindSignatures, LambdaCase #-}
{-# LANGUAGE MagicHash, MultiParamTypeClasses, MultiWayIf           #-}
{-# LANGUAGE NumericUnderscores, OverloadedStrings, PatternSynonyms #-}
{-# LANGUAGE RankNTypes, RecordWildCards, ScopedTypeVariables       #-}
{-# LANGUAGE StandaloneDeriving, TupleSections, TypeApplications    #-}
{-# LANGUAGE TypeFamilies, TypeInType, UnboxedTuples, ViewPatterns  #-}

import           Control.Applicative
import           Control.Exception
import           Control.Monad
import           Control.Monad.Primitive
import           Control.Monad.Reader
import           Control.Monad.ST
import           Control.Monad.State.Strict
import           Data.Bifunctor
import           Data.Bool
import qualified Data.ByteString                   as B
import qualified Data.ByteString.Builder           as B
import qualified Data.ByteString.Char8             as C
import qualified Data.ByteString.Internal          as B
import qualified Data.ByteString.Unsafe            as B
import           Data.Char
import qualified Data.Foldable                     as F
import           Data.Function
import           Data.Functor.Identity
import qualified Data.IntMap.Strict                as IM
import qualified Data.IntSet                       as IS
import qualified Data.List                         as L
import qualified Data.Map.Strict                   as M
import           Data.Monoid
import           Data.Ord
import           Data.Primitive
import           Data.Proxy
import           Data.Ratio
import           Data.Semigroup
import qualified Data.Set                          as S
import           Data.Tuple
import qualified Data.Vector                       as V
import qualified Data.Vector.Algorithms.Intro      as Intro
import qualified Data.Vector.Fusion.Stream.Monadic as MS
import qualified Data.Vector.Fusion.Bundle.Monadic as MB
import           Data.Vector.Fusion.Util
import qualified Data.Vector.Generic               as G
import qualified Data.Vector.Generic.Mutable       as GM
import qualified Data.Vector.Mutable               as VM
import qualified Data.Vector.Primitive             as P
import qualified Data.Vector.Primitive.Mutable     as PM
import qualified Data.Vector.Unboxed               as U
import qualified Data.Vector.Unboxed.Mutable       as UM
import           Debug.Trace
import           Foreign                           hiding (void)
import           GHC.Exts
import           GHC.TypeLits
import           System.IO
import           Unsafe.Coerce

#define MOD 1000000007
#define FACT_CACHE_SIZE 1100100

main :: IO ()
main = readLn>>=print.solve

solve :: Int -> IntMod
solve n = (10 ^ n) - 2 * (9 ^ n) + (8 ^ n)

-------------------------------------------------------------------------------
-- Utils
-------------------------------------------------------------------------------
rep :: (Monad m) => Int -> (Int -> m ()) -> m ()
rep n = flip MS.mapM_ (stream 0 n)
{-# INLINE rep #-}
rev :: (Monad m) => Int -> (Int -> m ()) -> m ()
rev !n = flip MS.mapM_ (streamR 0 n)
{-# INLINE rev #-}
stream :: (Monad m) => Int -> Int -> MS.Stream m Int
stream !l !r = MS.Stream step l where { step x | x < r = return $ MS.Yield x (x + 1) | otherwise = return MS.Done; {-# INLINE [0] step #-}}
{-# INLINE [1] stream #-}
streamR :: (Monad m) => Int -> Int -> MS.Stream m Int
streamR !l !r = MS.Stream step (r - 1) where { step x | x >= l = return $ MS.Yield x (x - 1) | otherwise = return MS.Done; {-# INLINE [0] step #-}}
{-# INLINE [1] streamR #-}
stream' :: (Monad m) => Int -> Int -> Int -> MS.Stream m Int
stream' !l !r !d = MS.Stream step l where { step x | x < r = return $ MS.Yield x (x + d) | otherwise = return MS.Done; {-# INLINE [0] step #-}}
{-# INLINE [1] stream' #-}
infixl 8 `shiftRL`, `unsafeShiftRL`
shiftRL :: Int -> Int -> Int
shiftRL = unsafeShiftRL
{-# INLINE shiftRL #-}
unsafeShiftRL :: Int -> Int -> Int
unsafeShiftRL (I# x#) (I# i#) = I# (uncheckedIShiftRL# x# i#)
{-# INLINE unsafeShiftRL #-}
type Parser a = StateT C.ByteString Maybe a
runParser :: Parser a -> C.ByteString -> Maybe (a, C.ByteString)
runParser = runStateT
{-# INLINE runParser #-}
int :: Parser Int
int = coerce $ C.readInt . C.dropWhile isSpace
{-# INLINE int #-}
int1 :: Parser Int
int1 = fmap (subtract 1) int
{-# INLINE int1 #-}
char :: Parser Char
char = coerce C.uncons
{-# INLINE char #-}
byte :: Parser Word8
byte = coerce B.uncons
{-# INLINE byte #-}
skipSpaces :: Parser ()
skipSpaces = modify' (C.dropWhile isSpace)
{-# INLINE skipSpaces #-}
lowerBoundM :: (Monad m) => Int -> Int -> (Int -> m Bool) -> m Int
lowerBoundM low high p = go low high where { go !low !high | high <= low = return high | otherwise = p mid >>= bool (go (mid + 1) high) (go low mid) where { mid = low + unsafeShiftRL (high - low) 1}}
{-# INLINE lowerBoundM #-}
upperBoundM :: (Monad m) => Int -> Int -> (Int -> m Bool) -> m Int
upperBoundM low high p = do { flg <- p high; if flg then return high else subtract 1 <$!> lowerBoundM low high (fmap not . p)}
{-# INLINE upperBoundM #-}
lowerBound :: Int -> Int -> (Int -> Bool) -> Int
lowerBound low high p = runIdentity (lowerBoundM low high (return . p))
{-# INLINE lowerBound #-}
upperBound :: Int -> Int -> (Int -> Bool) -> Int
upperBound low high p = runIdentity (upperBoundM low high (return . p))
{-# INLINE upperBound #-}
-------------------------------------------------------------------------------
-- Data.IntMod
-------------------------------------------------------------------------------
modulus :: (Num a) => a
modulus = MOD
{-# INLINE modulus #-}
infixr 8 ^%
infixl 7 *%, /%
infixl 6 +%, -%
(+%) :: Int -> Int -> Int
(I# x#) +% (I# y#) = case x# +# y# of { r# -> I# (r# -# ((r# >=# MOD#) *# MOD#))}
{-# INLINE (+%) #-}
(-%) :: Int -> Int -> Int
(I# x#) -% (I# y#) = case x# -# y# of { r# -> I# (r# +# ((r# <# 0#) *# MOD#))}
{-# INLINE (-%) #-}
(*%) :: Int -> Int -> Int
(I# x#) *% (I# y#) = I# ((x# *# y#) `remInt#` MOD#)
{-# INLINE (*%) #-}
(/%) :: Int -> Int -> Int
(I# x#) /% (I# y#) = go# y# MOD# 1# 0# where { go# a# b# u# v# | isTrue# (b# ># 0#) = case a# `quotInt#` b# of { q# -> go# b# (a# -# (q# *# b#)) v# (u# -# (q# *# v#))} | otherwise = I# ((x# *# (u# +# MOD#)) `remInt#` MOD#)}
{-# INLINE (/%) #-}
(^%) :: Int -> Int -> Int
x ^% n | n > 0 = go 1 x n | n == 0 = 1 | otherwise = go 1 (1 /% x) (-n) where { go !acc !y !m | m .&. 1 == 0 = go acc (y *% y) (unsafeShiftR m 1) | m == 1 = acc *% y | otherwise = go (acc *% y) (y *% y) (unsafeShiftR (m - 1) 1)}
newtype IntMod = IntMod{getIntMod :: Int} deriving newtype (Eq, Ord, Read, Show, Real, Prim)
intMod :: (Integral a) => a -> IntMod
intMod x = fromIntegral $ mod (fromIntegral x) MOD
{-# INLINE intMod #-}
intModValidate :: IntMod -> Bool
intModValidate (IntMod x) = 0 <= x && x < MOD
{-# INLINE intModValidate #-}
instance Bounded IntMod where { minBound = IntMod 0; maxBound = IntMod $ modulus - 1}
instance Enum IntMod where { toEnum = intMod; fromEnum = coerce}
instance Integral IntMod where { quotRem x y = (x / y, x - x / y * y); toInteger = coerce (toInteger @Int)}
instance Num IntMod where { (+) = coerce (+%); (-) = coerce (-%); (*) = coerce (*%); abs = id; signum = const (IntMod 1); fromInteger x = coerce @Int @IntMod . fromInteger $ mod x modulus}
instance Fractional IntMod where { (/) = coerce (/%); fromRational q = fromInteger (numerator q) / fromInteger (denominator q)}
newtype instance  UM.MVector s IntMod = MV_IntMod (UM.MVector s Int)
newtype instance  U.Vector IntMod = V_IntMod (U.Vector Int)
instance U.Unbox IntMod
instance GM.MVector UM.MVector IntMod where { basicLength (MV_IntMod v) = GM.basicLength v; {-# INLINE basicLength #-}; basicUnsafeSlice i n (MV_IntMod v) = MV_IntMod $ GM.basicUnsafeSlice i n v; {-# INLINE basicUnsafeSlice #-}; basicOverlaps (MV_IntMod v1) (MV_IntMod v2) = GM.basicOverlaps v1 v2; {-# INLINE basicOverlaps #-}; basicUnsafeNew n = MV_IntMod `liftM` GM.basicUnsafeNew n; {-# INLINE basicUnsafeNew #-}; basicInitialize (MV_IntMod v) = GM.basicInitialize v; {-# INLINE basicInitialize #-}; basicUnsafeReplicate n x = MV_IntMod `liftM` GM.basicUnsafeReplicate n (coerce x); {-# INLINE basicUnsafeReplicate #-}; basicUnsafeRead (MV_IntMod v) i = coerce `liftM` GM.basicUnsafeRead v i; {-# INLINE basicUnsafeRead #-}; basicUnsafeWrite (MV_IntMod v) i x = GM.basicUnsafeWrite v i (coerce x); {-# INLINE basicUnsafeWrite #-}; basicClear (MV_IntMod v) = GM.basicClear v; {-# INLINE basicClear #-}; basicSet (MV_IntMod v) x = GM.basicSet v (coerce x); {-# INLINE basicSet #-}; basicUnsafeCopy (MV_IntMod v1) (MV_IntMod v2) = GM.basicUnsafeCopy v1 v2; {-# INLINE basicUnsafeCopy #-}; basicUnsafeMove (MV_IntMod v1) (MV_IntMod v2) = GM.basicUnsafeMove v1 v2; {-# INLINE basicUnsafeMove #-}; basicUnsafeGrow (MV_IntMod v) n = MV_IntMod `liftM` GM.basicUnsafeGrow v n; {-# INLINE basicUnsafeGrow #-}}
instance G.Vector U.Vector IntMod where { basicUnsafeFreeze (MV_IntMod v) = V_IntMod `liftM` G.basicUnsafeFreeze v; {-# INLINE basicUnsafeFreeze #-}; basicUnsafeThaw (V_IntMod v) = MV_IntMod `liftM` G.basicUnsafeThaw v; {-# INLINE basicUnsafeThaw #-}; basicLength (V_IntMod v) = G.basicLength v; {-# INLINE basicLength #-}; basicUnsafeSlice i n (V_IntMod v) = V_IntMod $ G.basicUnsafeSlice i n v; {-# INLINE basicUnsafeSlice #-}; basicUnsafeIndexM (V_IntMod v) i = coerce `liftM` G.basicUnsafeIndexM v i; {-# INLINE basicUnsafeIndexM #-}; basicUnsafeCopy (MV_IntMod mv) (V_IntMod v) = G.basicUnsafeCopy mv v; elemseq _ = seq; {-# INLINE elemseq #-}}
-------------------------------------------------------------------------------
-- Math.Combinatrics
-------------------------------------------------------------------------------
fact :: Int -> IntMod
fact = U.unsafeIndex factCache
{-# INLINE fact #-}
recipFact :: Int -> IntMod
recipFact = U.unsafeIndex recipFactCache
{-# INLINE recipFact #-}
perm :: Int -> Int -> IntMod
perm n k = fact n * recipFact (n - k)
{-# INLINE perm #-}
comb :: Int -> Int -> IntMod
comb n k = fact n * recipFact (n - k) * recipFact k
{-# INLINE comb #-}
factCacheSize :: Int
factCacheSize = min (modulus - 1) FACT_CACHE_SIZE
{-# INLINE factCacheSize #-}
factCache :: U.Vector IntMod
factCache = U.scanl' (\ x y -> x * coerce y) (1 :: IntMod) $ U.generate factCacheSize (+ 1)
{-# NOINLINE factCache #-}
recipFactCache :: U.Vector IntMod
recipFactCache = U.scanr' ((*) . coerce) (1 / factCache U.! factCacheSize) $ U.generate factCacheSize (+ 1)
{-# NOINLINE recipFactCache #-}


-- https://github.com/minoki/my-atcoder-solutions
{-# LANGUAGE BangPatterns #-}
import           Control.Monad
import           Control.Monad.Primitive     (PrimMonad, PrimState)
import qualified Data.ByteString.Char8       as BS
import           Data.Char                   (isSpace)
import           Data.List                   (unfoldr)
import qualified Data.Vector.Unboxed         as U
import qualified Data.Vector.Unboxed.Mutable as UM

-- Union Find
newUnionFindTree :: PrimMonad m => Int -> m (UM.MVector (PrimState m) Int)
newUnionFindTree n = U.thaw $ U.enumFromN 0 n

getRoot :: PrimMonad m => UM.MVector (PrimState m) Int -> Int -> m Int
getRoot !v = go
  where
    go !i = do
      j <- UM.read v i
      if i == j then
        return i
      else do
        k <- go j
        UM.write v i k
        return k
{-# INLINE getRoot #-}

unify :: PrimMonad m => UM.MVector (PrimState m) Int -> Int -> Int -> m ()
unify !v !i !j = do
  i' <- getRoot v i
  j' <- getRoot v j
  unless (i' == j') $ do
    let !k = min i' j'
    UM.write v i' k
    UM.write v j' k
{-# INLINE unify #-}

main = do
  [n,q] <- unfoldr (BS.readInt . BS.dropWhile isSpace) <$> BS.getLine
  uf <- newUnionFindTree n
  replicateM_ q $ do
    [t,u,v] <- unfoldr (BS.readInt . BS.dropWhile isSpace) <$> BS.getLine
    if t == 0 then
      unify uf u v
    else do
      i <- getRoot uf u
      j <- getRoot uf v
      putStrLn $ if i == j then "1" else "0"

Score : 100 points

Problem Statement

You are given an undirected graph with N vertices and 0 edges. Process Q queries of the following types.

0 u v: Add an edge (u, v).

1 u v: Print 1 if u and v are in the same connected component, 0 otherwise.

Constraints

1 \leq N \leq 200,000

1 \leq Q \leq 200,000

0 \leq u_i, v_i \lt N

Input

Input is given from Standard Input in the following format:

N Q
t_1 u_1 v_1
t_2 u_2 v_2
:
t_Q u_Q v_Q

出力

For each query of the latter type, print the answer.

Sample Input 1

4 7
1 0 1
0 0 1
0 2 3
1 0 1
1 1 2
0 0 2
1 1 3

Sample Output 1

0
1
0
1


{-# LANGUAGE MultiWayIf #-}

module Main where

import Control.Monad
import Control.Monad.Extra
import qualified Data.Array as A
import qualified Data.Array.IO as AIO
import qualified Data.Array.Unboxed as AU
import Data.Bits
import Data.Bool
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BSC8
import Data.Char
import Data.Either
import Data.Function
import qualified Data.Graph.Inductive.Graph as G
import qualified Data.Graph.Inductive.PatriciaTree as G
import qualified Data.Heap as H
import Data.Int
import Data.List
import qualified Data.Map.Strict as M
import Data.Maybe
import Data.Monoid
import Data.Ord
import qualified Data.Sequence as SQ
import qualified Data.Set as S
import Data.Tuple
import qualified Data.Vector as V
import Data.Vector.Algorithms.Search
import qualified Data.Vector.Mutable as VM
import qualified Data.Vector.Unboxed as VU
import qualified Data.Vector.Unboxed.Mutable as VUM
import Debug.Trace
import GHC.Base

main = do
  --aN       <- getI
  --[aA, aB] <- getIL
  --aS       <- getLine
  [aN, aM] <- getIL
  iniGraph <-
    V.thaw
      =<< ( V.generateM (aN * aM + 2) $
              ( \i ->
                  if
                      | i >= aN * aM ->
                        VUM.replicate
                          (div (aN * aM) 2 + 1)
                          (0 :: Int, 0 :: Int, 0 :: Int)
                      | otherwise -> VUM.replicate 5 (0 :: Int, 0 :: Int, 0 :: Int)
              )
          )
  graphData <- aclMaxFlowGraph (aN * aM + 2) (aN * aM * 6) iniGraph
  let s = aN * aM
  let t = aN * aM + 1
  grid <- V.replicateM aN getVUC
  graphDataAdd1 <-
    VU.foldM
      ( \acc1 i ->
          VU.foldM
            ( \acc2 j ->
                let v = i * aM + j
                 in if grid V.! i VU.! j == '#'
                      then return acc2
                      else
                        if even (i + j)
                          then aclMaxFlowAddEdge acc2 s v 1
                          else aclMaxFlowAddEdge acc2 v t 1
            )
            acc1
            (VU.enumFromN 0 aM)
      )
      graphData
      (VU.enumFromN 0 aN)
  graphDataAdd2@(_, _, graphLen, _, graph, _) <-
    VU.foldM
      ( \acc1 i ->
          VU.foldM
            ( \acc2 j ->
                let v0 = i * aM + j
                 in VU.foldM
                      ( \acc3 k@(ky, kx) ->
                          let v1 = kx + (ky * aM)
                           in if odd (i + j) || grid V.! i VU.! j == '#'
                                then return acc3
                                else
                                  if grid V.! ky VU.! kx == '.'
                                    then aclMaxFlowAddEdge acc3 v0 v1 1
                                    else return acc3
                      )
                      acc2
                      $ aroundSquare i j aN aM
            )
            acc1
            (VU.enumFromN 0 aM)
      )
      graphDataAdd1
      (VU.enumFromN 0 aN)
  {-
  print "graph1"
  V.imapM_
    (\i x -> do
       fx <- VU.freeze x
       print $ show i ++ ":" ++ show fx)
    =<< (V.freeze graph)
  print "graphLen1"
  print =<< VU.freeze graphLen
  -}
  flow <- aclMaxFlowFlow graphDataAdd2 s t
  print flow
  {-
   print "graph2"
   V.imapM_
     (\i x -> do
        fx <- VU.freeze x
        print $ show i ++ ":" ++ show fx)
     =<< (V.freeze graph)
   print "graphLen2"
   print =<< VU.freeze graphLen
  -}
  edges <- aclMaxFlowEdges graphDataAdd2
  --print edges
  --print =<< VU.freeze pos2
  newGrid <- V.thaw =<< (V.generateM aN $ \i -> VU.thaw $ grid V.! i)
  VU.mapM_
    ( \e@(from, to, cap, flow) -> do
        if from == s || to == t || flow == 0
          then return ()
          else do
            let i0 = div from aM
                j0 = mod from aM
                i1 = div to aM
                j1 = mod to aM
            newGridI0 <- VM.unsafeRead newGrid i0
            newGridI1 <- VM.unsafeRead newGrid i1
            if
                | i0 == i1 + 1 -> do
                  VUM.unsafeWrite newGridI1 j1 'v'
                  VUM.unsafeWrite newGridI0 j0 '^'
                | j0 == j1 + 1 -> do
                  VUM.unsafeWrite newGridI1 j1 '>'
                  VUM.unsafeWrite newGridI0 j0 '<'
                | i0 == i1 - 1 -> do
                  VUM.unsafeWrite newGridI0 j0 'v'
                  VUM.unsafeWrite newGridI1 j1 '^'
                | otherwise -> do
                  VUM.unsafeWrite newGridI0 j0 '>'
                  VUM.unsafeWrite newGridI1 j1 '<'
    )
    edges
  V.mapM_ (\newGridI -> putStrLn =<< VU.toList <$> VU.freeze newGridI)
    =<< V.freeze newGrid
  return ()

--雑多系
t :: Int -> (Int, Int)
t x = (x, 1)

i def f t = bool t def $ f t

shiftRCnt k = shiftRCntP k 1

shiftRCntP k c =
  let nk = shiftR k 1
   in if nk == 0
        then c
        else shiftRCntP nk (c + 1)

myVUmap f vu =
  if vu == VU.empty
    then VU.empty
    else
      VU.unfoldr
        ( \x ->
            let ret = f $ VU.head x
                tailx = VU.tail x
             in if x == VU.empty
                  then Nothing
                  else
                    if isLeft ret
                      then Just (either id id ret, tailx)
                      else Just (either id id ret, VU.empty)
        )
        vu

myVUmapM f vu =
  if vu == VU.empty
    then return VU.empty
    else
      VU.unfoldrM
        ( \x -> do
            ret <- f $ VU.head x
            let tailx = VU.tail x
            if x == VU.empty
              then return Nothing
              else
                if isLeft ret
                  then return $ Just (either id id ret, tailx)
                  else return $ Just (either id id ret, VU.empty)
        )
        vu

myVUmapM_ f vu =
  if vu == VU.empty
    then return ()
    else do
      ret1 <-
        VU.unfoldrM
          ( \x -> do
              ret2 <- f $ VU.head x
              let tailx = VU.tail x
              if x == VU.empty
                then return Nothing
                else
                  if isLeft ret2
                    then return $ Just (either id id ret2, tailx)
                    else return $ Just (either id id ret2, VU.empty)
          )
          vu
      return ()

myVUfor vu f = myVUmap f vu

myVUforM vu f = myVUmapM f vu

myVUforM_ vu f = myVUmapM_ f vu

myVUfoldl f acc vu =
  if vu == VU.empty
    then return acc
    else do
      let ret = f acc (VU.head vu)
      if isLeft ret
        then myVUfoldl f (either id id ret) (VU.tail vu)
        else return $ either id id ret

myVUfoldr f acc vu =
  if vu == VU.empty
    then return acc
    else do
      let ret = f acc (VU.last vu)
      if isLeft ret
        then myVUfoldr f (either id id ret) (VU.init vu)
        else return $ either id id ret

myVUfoldM f acc vu =
  if vu == VU.empty
    then return acc
    else do
      ret <- f acc (VU.head vu)
      if isLeft ret
        then myVUfoldM f (either id id ret) (VU.tail vu)
        else return $ either id id ret

--周りのマス
aroundSquare y x h w =
  VU.concatMap
    ( \a ->
        VU.mapMaybe
          ( \b ->
              let ya = y + a
                  xb = x + b
               in if abs a + abs b == 1
                    then
                      if ya < 0 || ya >= h || xb < 0 || xb >= w
                        then Nothing
                        else Just (ya, xb)
                    else Nothing
          )
          $ VU.enumFromN (-1) 3
    )
    $ VU.enumFromN (-1) 3

--入力系
splitReadBSC8 :: BSC8.ByteString -> [Int]
splitReadBSC8 bs =
  let (bs1, newBs) = BSC8.splitAt 1 bs
   in if newBs == BSC8.empty
        then [test $ BSC8.readInt bs1]
        else test (BSC8.readInt bs1) : splitReadBSC8 newBs
  where
    test (Just (i, _)) = i

read2DimChar :: VM.IOVector (VUM.IOVector Char) -> Int -> Int -> IO Char
read2DimChar vec y x = do
  vecY <- VM.unsafeRead vec y
  VUM.unsafeRead vecY x

write2DimChar :: VM.IOVector (VUM.IOVector Char) -> Int -> Int -> Char -> IO ()
write2DimChar vec y x t = do
  vecY <- VM.unsafeRead vec y
  VUM.unsafeWrite vecY x t

readTwoDimVec :: VM.IOVector (VUM.IOVector Int) -> Int -> Int -> IO Int
readTwoDimVec vec y x = do
  vecY <- VM.unsafeRead vec y
  VUM.unsafeRead vecY x

writeTwoDimVec :: VM.IOVector (VUM.IOVector Int) -> Int -> Int -> Int -> IO ()
writeTwoDimVec vec y x t = do
  vecY <- VM.unsafeRead vec y
  VUM.unsafeWrite vecY x t

getVUI :: IO (VU.Vector Int)
getVUI = VU.unfoldr (BSC8.readInt . BSC8.dropWhile isSpace) <$> BSC8.getLine

getRepVUI :: Int -> IO (VU.Vector Int)
getRepVUI n =
  VU.unfoldr (BSC8.readInt . BSC8.dropWhile isSpace) . BSC8.unlines
    <$> replicateM n BSC8.getLine

getVS :: IO (V.Vector Char)
getVS = V.fromList <$> getLine

getVUC :: IO (VU.Vector Char)
getVUC = VU.fromList <$> getLine

readI :: BSC8.ByteString -> Int
readI = fst . fromJust . BSC8.readInt

readInteger :: BSC8.ByteString -> Integer
readInteger = fst . fromJust . BSC8.readInteger

readIL :: BSC8.ByteString -> [Int]
readIL = map readI . BSC8.words

readIT2 :: BSC8.ByteString -> (Int, Int)
readIT2 bs =
  let words = BSC8.words bs
   in (readI $ head words, readI $ last words)

readIT3 :: BSC8.ByteString -> (Int, Int, Int)
readIT3 bs =
  let words = BSC8.words bs
   in (readI $ head words, readI $ words !! 1, readI $ words !! 2)

getI :: IO Int
getI = readI <$> BSC8.getLine

getInteger :: IO Integer
getInteger = readInteger <$> BSC8.getLine

getIL :: IO [Int]
getIL = readIL <$> BSC8.getLine

getIT2 :: IO (Int, Int)
getIT2 = readIT2 <$> BSC8.getLine

getIT3 :: IO (Int, Int, Int)
getIT3 = readIT3 <$> BSC8.getLine

getIT2Order :: IO (Int, Int)
getIT2Order =
  getIL
    >>= \x@[xz, xo] ->
      if xz > xo
        then return (xo, xz)
        else return (xz, xo)

getNIS :: Int -> IO [(Int, BSC8.ByteString)]
getNIS 0 = return []
getNIS n = do
  [aFst, aSnd] <- BSC8.words <$> BSC8.getLine
  next <- getNIS (n - 1)
  return ((readI aFst, aSnd) : next)

il2Words :: [Int] -> String
il2Words = unwords . map show

il2Lines :: [Int] -> String
il2Lines = unlines . map show

---MaxFlow
{-aclMaxFlowGraph n = (,,) n <$> VM.replicateM n (VUM.replicate 0 (0, 0, 0))
  <*> VU.thaw VU.empty
-}
{-
  aclMaxFlowAddAllEdges graphData $ VU.singleton (from, to, cap)

bkaclMaxFlowAddAllEdges graphData@(n, graph, pos) edges = do
  (addPos, addGraphMap) <- VU.foldM
    (\acc@(accPos, accGraphMap) edge@(from, to, cap) -> if
       | from < 0 || n <= from -> error
         "aclMaxFlowAddEdge:fromを0以上nより小さい値になるように見直してください。"
       | to < 0 || n <= to -> error
         "aclMaxFlowAddEdge:toを0以上nより小さい値になるように見直してください。"
       | cap < 0 -> error
         "aclMaxFlowAddEdge:capを0以上の値になるように見直してください。"
       | otherwise -> do
         gFrom <- VM.unsafeRead graph from
         gTo <- VM.unsafeRead graph to
         let gFromSize = VUM.length gFrom
             gToSize = VUM.length gTo
             accGFrom = M.findWithDefault [] from accGraphMap
             accGTo = M.findWithDefault [] to accGraphMap
             accGFromSize = length accGFrom
             accGToSize = length accGTo
             sumGFromSize = gFromSize + accGFromSize
             sumGToSize = gToSize + accGToSize
         return
           ( (from, sumGFromSize):accPos
           , M.insert
               to
               ((from, sumGFromSize, 0):accGTo)
               (M.insert from ((to, sumGToSize, cap):accGFrom) accGraphMap)))
    ([], M.empty)
    edges
  nGraph <- V.thaw
    =<< V.mapM
      (\i -> do
         oGraph <- VU.freeze =<< VM.unsafeRead graph i
         let nGraph = oGraph
               VU.++ (VU.fromList
                      $ reverse (M.findWithDefault [] i addGraphMap))
         VU.thaw nGraph)
      (V.enumFromN 0 n)
  nPos <- VU.thaw =<< ((VU.++ VU.fromList addPos) <$> VU.freeze pos)
  return (n, nGraph, nPos)
-}
{-aclMaxFlowGraph
  :: Int -> IO (Int, VM.IOVector (SQ.Seq (Int, Int, Int)), SQ.Seq (Int, Int))
aclMaxFlowGraph n = do
  graphIni <- VM.replicate n (SQ.empty)
  return (n, graphIni, SQ.empty)

aclMaxFlowAddEdge
  :: (Int, VM.IOVector (SQ.Seq (Int, Int, Int)), SQ.Seq (Int, Int))
  -> Int
  -> Int
  -> Int
  -> IO (Int, (Int, VM.IOVector (SQ.Seq (Int, Int, Int)), SQ.Seq (Int, Int)))
aclMaxFlowAddEdge graphIniData@(iniN, iniGraph, iniPos) from to cap = if
  | from < 0 || iniN <= from -> error
    "aclMaxFlowAddEdge:fromを0以上nより小さい値になるように見直してください。"
  | to < 0 || iniN <= to -> error
    "aclMaxFlowAddEdge:toを0以上nより小さい値になるように見直してください。"
  | cap < 0 -> error
    "aclMaxFlowAddEdge:capを0以上の値になるように見直してください。"
  | otherwise -> do
    let m = SQ.length iniPos
    graphFrom <- VM.unsafeRead iniGraph from
    graphTo <- VM.unsafeRead iniGraph to
    let graphFromSize = SQ.length graphFrom
    let graphToSize = SQ.length graphTo
    VM.unsafeWrite iniGraph from (graphFrom SQ.|> (to, graphToSize, cap))
    VM.unsafeWrite iniGraph to (graphTo SQ.|> (from, graphFromSize, 0))
    return (m, (iniN, iniGraph, iniPos SQ.|> (from, graphFromSize)))

aclMaxFlowConvertIniData
  :: (Int, VM.IOVector (SQ.Seq (Int, Int, Int)), SQ.Seq (Int, Int))
  -> IO
    (Int, VM.IOVector (VUM.IOVector (Int, Int, Int)), VUM.IOVector (Int, Int))
aclMaxFlowConvertIniData graphIniData@(iniN, iniGraph, iniPos) = do
  graph <- V.thaw
    =<< (V.generateM
           iniN
           (\i -> do
              seq <- VM.unsafeRead iniGraph i
              VU.thaw
                $ VU.unfoldr
                  (\x -> let (s SQ.:< sn) = SQ.viewl x
                         in if x == SQ.empty
                            then Nothing
                            else Just (s, sn))
                  seq))
  pos <- VU.thaw
    $ VU.unfoldr
      (\x -> let (s SQ.:< sn) = SQ.viewl x
             in if x == SQ.empty
                then Nothing
                else Just (s, sn))
      iniPos
  return (iniN, graph, pos)-}
aclMaxFlowGraph ::
  Int ->
  Int ->
  VM.IOVector (VUM.IOVector (Int, Int, Int)) ->
  IO
    ( Int,
      Int,
      VUM.IOVector (Int),
      Int,
      VM.IOVector (VUM.IOVector (Int, Int, Int)),
      VUM.IOVector (Int, Int)
    )
aclMaxFlowGraph n m iniGraph = do
  pos <- VUM.replicate m (0, 0)
  graphLen <- VUM.replicate n 0
  return (n, m, graphLen, 0, iniGraph, pos)

aclMaxFlowAddEdge ::
  ( Int,
    Int,
    VUM.IOVector (Int),
    Int,
    VM.IOVector (VUM.IOVector (Int, Int, Int)),
    VUM.IOVector (Int, Int)
  ) ->
  Int ->
  Int ->
  Int ->
  IO
    ( Int,
      Int,
      VUM.IOVector (Int),
      Int,
      VM.IOVector (VUM.IOVector (Int, Int, Int)),
      VUM.IOVector (Int, Int)
    )
aclMaxFlowAddEdge graphData@(n, m, graphLen, posLen, graph, pos) from to cap =
  if
      | from < 0 || n <= from ->
        error
          "aclMaxFlowAddEdge:fromを0以上nより小さい値になるように見直してください。"
      | to < 0 || n <= to ->
        error
          "aclMaxFlowAddEdge:toを0以上nより小さい値になるように見直してください。"
      | cap < 0 ->
        error
          "aclMaxFlowAddEdge:capを0以上の値になるように見直してください。"
      | otherwise -> do
        graphFrom <- VM.unsafeRead graph from
        graphTo <- VM.unsafeRead graph to
        graphFromSize <- VUM.unsafeRead graphLen from
        graphToSize <- VUM.unsafeRead graphLen to
        VUM.unsafeWrite graphFrom graphFromSize (to, graphToSize, cap)
        VUM.unsafeWrite graphTo graphToSize (from, graphFromSize, 0)
        VUM.unsafeWrite pos posLen (from, graphFromSize)
        VUM.unsafeModify graphLen succ from
        VUM.unsafeModify graphLen succ to
        return (n, m, graphLen, posLen + 1, graph, pos)

aclMaxFlowGetEdge graphData@(n, m, graphLen, posLen, graph, pos) i =
  let m = posLen
   in if i < 0 || m <= i
        then
          error
            "aclMaxFlowAddEdge:iを0以上mより小さい値になるように見直してください。"
        else do
          posi <- VUM.unsafeRead pos i
          graphi <- VM.unsafeRead graph (fst posi)
          e@(eTo, eRev, eCap) <- VUM.unsafeRead graphi (snd posi)
          graphTo <- VM.unsafeRead graph eTo
          re@(reTo, reRev, reCap) <- VUM.unsafeRead graphTo eRev
          return (fst posi, eTo, eCap + reCap, reCap)

aclMaxFlowEdges graphData@(n, m, graphLen, posLen, graph, pos) =
  let m = posLen
   in VU.mapM (aclMaxFlowGetEdge graphData) $ VU.enumFromN 0 m

aclMaxFlowChangeEdge
  graphData@(n, m, graphLen, posLen, graph, pos)
  i
  newCap
  newFlow = do
    let m = posLen
    if i < 0 || m <= i
      then
        error
          "aclMaxFlowAddEdge:iを0以上mより小さい値になるように見直してください。"
      else do
        posi <- VUM.unsafeRead pos i
        graphA <- VM.unsafeRead graph (fst posi)
        e@(eTo, eRev, eCap) <- VUM.unsafeRead graphA (snd posi)
        graphB <- VM.unsafeRead graph eTo
        re@(reTo, reRev, reCap) <- VUM.unsafeRead graphB eRev
        return ()

aclMaxFlowFlow graphData@(n, m, graphLen, posLen, graph, pos) s t =
  aclMaxFlowFlowLimit graphData s t maxInt

aclMaxFlowFlowLimit ::
  ( Int,
    Int,
    VUM.IOVector (Int),
    Int,
    VM.IOVector (VUM.IOVector (Int, Int, Int)),
    VUM.IOVector (Int, Int)
  ) ->
  Int ->
  Int ->
  Int ->
  IO Int
aclMaxFlowFlowLimit
  graphData@(n, m, graphLen, posLen, graph, pos)
  s
  t
  flowLimit
    | s < 0 || n <= s =
      error
        "aclMaxFlowFlow:sを0以上nより小さい値になるように見直してください。"
    | t < 0 || n <= t =
      error
        "aclMaxFlowFlow:tを0以上nより小さい値になるように見直してください。"
    | otherwise = do
      level <- VUM.new n :: IO (VUM.IOVector Int)
      iter <- VUM.new n :: IO (VUM.IOVector Int)
      aloop level iter 0
    where
      aloop :: VUM.IOVector Int -> VUM.IOVector Int -> Int -> IO Int
      aloop level iter flow =
        if flow >= flowLimit
          then return flow
          else do
            VUM.set level (-1)
            VUM.unsafeWrite level s 0
            level <- bfs level (SQ.singleton s)
            levelt <- VUM.unsafeRead level t
            if levelt < 0
              then return flow
              else do
                VUM.set iter 0
                nFlow <- bloop level iter flow
                aloop level iter nFlow

      bfs :: VUM.IOVector Int -> SQ.Seq (Int) -> IO (VUM.IOVector Int)
      bfs level sq
        | sq == SQ.empty = return level
        | otherwise = do
          let (sqh SQ.:< sqt) = SQ.viewl sq
          edges <- VM.unsafeRead graph sqh
          lenEdges <- VUM.unsafeRead graphLen sqh
          nSq <- cloop level edges 0 lenEdges sqh sqt
          bfs level nSq

      cloop ::
        VUM.IOVector Int ->
        VUM.IOVector (Int, Int, Int) ->
        Int ->
        Int ->
        Int ->
        SQ.Seq (Int) ->
        IO (SQ.Seq (Int))
      cloop level edges i edgesLen v sqt = do
        if i >= edgesLen
          then return sqt
          else do
            edge@(to, rev, cap) <- VUM.unsafeRead edges i
            levelTo <- VUM.unsafeRead level to
            if cap <= 0 || levelTo >= 0
              then cloop level edges (i + 1) edgesLen v sqt
              else do
                levelv <- VUM.unsafeRead level v
                VUM.unsafeWrite level to (levelv + 1)
                if to == t
                  then return sqt
                  else cloop level edges (i + 1) edgesLen v (to SQ.<| sqt)

      bloop :: VUM.IOVector Int -> VUM.IOVector Int -> Int -> IO Int
      bloop level iter flow
        | flow >= flowLimit = return flow
        | otherwise = do
          f <-
            if t == s
              then return (flowLimit - flow)
              else do
                levelV <- VUM.unsafeRead level t
                graphV <- VM.unsafeRead graph t
                lenGraphV <- VUM.unsafeRead graphLen t
                dfs graphV lenGraphV level 0 levelV t iter (flowLimit - flow) 0
          if f <= 0
            then return flow
            else bloop level iter (flow + f)

      dfs ::
        VUM.IOVector (Int, Int, Int) ->
        Int ->
        VUM.IOVector Int ->
        Int ->
        Int ->
        Int ->
        VUM.IOVector Int ->
        Int ->
        Int ->
        IO Int
      dfs graphV lenGraphV level i levelV v iter up res = do
        if i >= lenGraphV
          then do
            VUM.modify iter succ v
            return res
          else do
            VUM.modify iter succ v
            edge@(to, rev, cap) <- VUM.unsafeRead graphV i
            levelTo <- VUM.unsafeRead level to
            graphTo <- VM.unsafeRead graph to
            lenGraphTo <- VUM.unsafeRead graphLen to
            graphToRev@(nTo, nRev, nCap) <- VUM.unsafeRead graphTo rev
            if levelV <= levelTo || nCap <= 0
              then do
                dfs graphV lenGraphV level (i + 1) levelV v iter up res
              else do
                d <-
                  if to == s
                    then do
                      return (min (up - res) nCap)
                    else do
                      ni <- VUM.unsafeRead iter to
                      dfs
                        graphTo
                        lenGraphTo
                        level
                        ni
                        levelTo
                        to
                        iter
                        (min (up - res) nCap)
                        0
                if d <= 0
                  then dfs graphV lenGraphV level (i + 1) levelV v iter up res
                  else do
                    edge@(to2, rev2, cap2) <- VUM.unsafeRead graphV i
                    graphToRev@(nTo2, nRev2, nCap2) <- VUM.unsafeRead graphTo rev
                    VUM.unsafeWrite graphV i (to2, rev2, cap2 + d)
                    VUM.unsafeWrite graphTo rev (nTo2, nRev2, nCap2 - d)
                    let nres = res + d
                    if nres == up
                      then return nres
                      else dfs graphV lenGraphV level (i + i) levelV v iter up nres

aclMaxFlowMinCut graphData@(n, graph, pos) s = do
  visited <- VUM.replicate n False
  let sq = SQ.singleton s
  aloop visited sq
  VU.freeze visited
  where
    aloop visited sq
      | sq == SQ.empty = return ()
      | otherwise = do
        let (sqh SQ.:< sqt) = SQ.viewl sq
        VUM.unsafeWrite visited sqh True
        edges <- VM.unsafeRead graph sqh
        bloop visited edges 0 sq

    bloop visited edges i sq = do
      edge@(to, rev, cap) <- VUM.unsafeRead edges i
      visitedTo <- VUM.unsafeRead visited to
      if cap /= 0 && visitedTo == False
        then do
          VUM.unsafeWrite visited to True
          bloop visited edges i (to SQ.<| sq)
        else bloop visited edges i sq

---MinCostFlow後回し
---Convolution

Score : 100 points

Problem Statement

You are given a grid of N rows and M columns. The square at the i-th row and j-th column will be denoted as (i,j).
Some of the squares contain an object. All the remaining squares are empty.
The state of the grid is represented by strings S_1,S_2,\cdots,S_N. The square (i,j) contains an object if S_{i,j}= # and is empty if S_{i,j}= ..

Consider placing 1 \times 2 tiles on the grid. Tiles can be placed vertically or horizontally to cover two adjacent empty squares.
Tiles must not stick out of the grid, and no two different tiles may intersect. Tiles cannot occupy the square with an object.

Calculate the maximum number of tiles that can be placed and any configulation that acheives the maximum.

Constraints

1 \leq N \leq 100

1 \leq M \leq 100

S_i is a string with length M consists of # and ..

Input

Input is given from Standard Input in the following format:

N M
S_1
S_2
\vdots
S_N

Output

On the first line, print the maximum number of tiles that can be placed.

On the next N lines, print a configulation that achieves the maximum.
Precisely, output the strings t_1,t_2,\cdots,t_N constructed by the following way.

t_i is initialized to S_i.

For each (i,j), if there is a tile that occupies (i,j) and (i+1,j), change t_{i,j}:=v, t_{i+1,j}:=^.

For each (i,j), if there is a tile that occupies (i,j) and (i,j+1), change t_{i,j}:=>, t_{i,j+1}:=<.

See samples for further information.

You may print any configulation that maximizes the number of tiles.

Sample Input 1

3 3
#..
..#
...

Sample Output 1

3
#><
vv#
^^.

The following output is also treated as a correct answer.

3
#><
v.#
^><