Once Divan analyzed a sequence $$$a_1, a_2, \ldots, a_n$$$ consisting of $$$n$$$ non-negative integers as follows. He considered each non-empty subsequence of the sequence $$$a$$$, computed the bitwise XOR of its elements and added up all the XORs, obtaining the coziness of the sequence $$$a$$$.A sequence $$$c$$$ is a subsequence of a sequence $$$d$$$ if $$$c$$$ can be obtained from $$$d$$$ by deletion of several (possibly, zero or all) elements. For example, $$$[1, \, 2, \, 3, \, 4]$$$, $$$[2, \, 4]$$$, and $$$[2]$$$ are subsequences of $$$[1, \, 2, \, 3, \, 4]$$$, but $$$[4, \, 3]$$$ and $$$[0]$$$ are not.Divan was very proud of his analysis, but now he lost the sequence $$$a$$$, and also the coziness value! However, Divan remembers the value of bitwise OR on $$$m$$$ contiguous subsegments of the sequence $$$a$$$. It turns out that each element of the original sequence is contained in at least one of these $$$m$$$ segments.Divan asks you to help find the coziness of the sequence $$$a$$$ using the information he remembers. If several coziness values are possible, print any.As the result can be very large, print the value modulo $$$10^9 + 7$$$.

The first line contains one integer number $$$t$$$ ($$$1 \le t \le 10^3$$$) — the number of test cases. The first line of each test case contains two integer numbers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 2 \cdot 10^5$$$) — the length of the sequence and the number of contiguous segments whose bitwise OR values Divan remembers, respectively. The following $$$m$$$ lines describe the segments, one per line. Each segment is described with three integers $$$l$$$, $$$r$$$, and $$$x$$$ ($$$1 \le l \le r \le n$$$, $$$0 \le x \le 2^{30} - 1$$$) — the first and last elements of the segment and the bitwise OR of $$$a_l, a_{l + 1}, \ldots, a_r$$$, respectively. It is guaranteed that each element of the sequence is contained in at least one of the segments. It is guaranteed that there exists a sequence that satisfies all constraints. It is guaranteed that the sum of $$$n$$$ and the sum of $$$m$$$ over all test cases do not exceed $$$2 \cdot 10^5$$$.

For each test case print the coziness any suitable sequence $$$a$$$ modulo $$$10^9 + 7$$$.

NoteIn first example, one of the sequences that fits the constraints is $$$[0, 2]$$$. Consider all its non-empty subsequences:  $$$[0]$$$: the bitwise XOR of this subsequence is $$$0$$$;  $$$[2]$$$: the bitwise XOR of this subsequence is $$$2$$$;  $$$[0, 2]$$$: the bitwise XOR of this subsequence is $$$2$$$. The sum of all results is $$$4$$$, so it is the answer.In second example, one of the sequences that fits the constraints is $$$[0, \, 5, \, 5]$$$.In third example, one of the sequences that fits the constraints is $$$[5, \, 6, \, 7, \, 0, \, 2]$$$.

{-# LANGUAGE DeriveTraversable #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -funfolding-use-threshold=16 #-}
{-# OPTIONS_GHC -O2 #-}
{-# OPTIONS_GHC -optc-O3 #-}

module Main where

import           Control.Exception              ( Exception )
import           Control.Monad                  ( replicateM_, foldM_, replicateM )
import           Data.Array.Unboxed             ( (!)
                                                , (//)
                                                , UArray
                                                , listArray
                                                )
import qualified Data.ByteString.Char8         as C
import           Data.List                      ( foldl'
                                                , mapAccumL
                                                , unfoldr
                                                )
import           Prelude                 hiding ( replicate )
import Text.Printf (printf)
import Data.Functor (($>))
import Data.Bits ((.|.), shiftL)

-- arrange :: [a] -> Int -> [[a]]
-- arrange xs n = mapM (const xs) [1 .. n]

-- data Tree a = Null | Branch a (Tree a) (Tree a)
--   deriving (Show, Eq, Functor)

-- makeBaseFunctor ''Tree

-- x :: Tree Int
-- x = Branch 1 (Branch 2 Null Null) (Branch 3 Null Null)

-- y :: Tree Int -> Int
-- y = cata $ \case
--     NullF         -> 0
--     BranchF x a b -> x + a + b

-- >>> y x
-- 6

-- z :: Tree Int -> Int
-- z = para $ \case
--     NullF                     -> 0
--     BranchF x (x1, a) (x2, b) -> x + a + b + y x1 + y x2

-- >>> z x
-- 11

-- quicksort :: Ord a => [a] -> [a]
-- quicksort = hylo merge split  where
--     split []       = NullF
--     split (x : xs) = let (l, r) = partition (< x) xs in BranchF x l r

--     merge NullF           = []
--     merge (BranchF x l r) = l ++ [x] ++ r

-- >>> quicksort ([5,4,6,7,8,6,4,2])
-- [2,4,4,5,6,6,7,8]

-- fibSeq :: [Int]
-- fibSeq = futu phi Nil
--   where
--     phi Nil                    = Cons 0 (Pure (Cons 0 Nil))
--     phi x@(Cons _ Nil        ) = Cons 1 (Pure (Cons 1 (Cons 0 Nil)))
--     phi t@(Cons x (Cons y xs)) = Cons (x + y) (Pure (Cons (x + y) (Cons x Nil)))

-- >>> take 20 fibSeq
-- [0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181]

-- f1 :: [Int] -> Int
-- f1 = flip runReader 0 . cataA phi
--   where
--     phi Nil        = return 0
--     phi (Cons x t) = do
--         n <- ask
--         if n >= 10 then return 0 else (x +) <$> local succ t

-- f2 :: [Int]
-- f2 = apo phi 1
--   where
--     phi n | n < 100   = Cons (n * 2) (Right (n + 1))
--           | otherwise = Cons (n * 2) (Left [1, 2, 3])

-- >>> f1 fibSeq
-- 88

-- >>> f2
-- [2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,80,82,84,86,88,90,92,94,96,98,100,102,104,106,108,110,112,114,116,118,120,122,124,126,128,130,132,134,136,138,140,142,144,146,148,150,152,154,156,158,160,162,164,166,168,170,172,174,176,178,180,182,184,186,188,190,192,194,196,198]

-- urlParser :: Parser String
-- urlParser = argument str (metavar "URL")

-- segmented :: Int -> Int -> [(Int, Int)]
-- segmented total blocksize = (id &&& (min (total - 1) . (+ (blocksize - 1)))) <$> takeWhile (< total) [0, blocksize ..]

-- main :: IO ()
-- main = do
--     manager <- newManager tlsManagerSettings
--     url     <- execParser opts
--     req     <- parseRequest url
--     res     <- httpNoBody req manager
--     let len = maybe 0 fst (readInt =<< (lookup "Content-Length" (requestHeaders req) <|> lookup "content-length" (responseHeaders res)))
--     if len == 0
--         then do
--             res <- httpLbs req manager
--             print $ responseStatus res
--             print $ responseBody res
--         else do
--             pool <- createPool (pure ()) (const (pure ())) 2 0.5 5
--             mapConcurrently_
--                 (\(s, e) -> withResource pool $ \_ -> do
--                     res <- httpLbs (req { requestHeaders = ("Range", BS.pack $ formatToString ("bytes=" % int % "-" % int) s e) : requestHeaders req }) manager
--                     print $ responseStatus res
--                     -- print $ responseBody res
--                 )
--                 (segmented len tenMegabytes)
--   where
--     opts         = info urlParser fullDesc
--     tenMegabytes = 10485760

data Break = Break
    deriving Show

instance Exception Break

readChar8 :: IO [Int]
readChar8 = map parse . C.words <$> C.getLine where parse s = let Just (n, _) = C.readInt s in n

readChar8' :: IO [Int]
readChar8' = parse <$> C.getLine
  where
    parse = unfoldr go
    go s = do
        (n, s1) <- C.readInt s
        let s2 = C.dropWhile (== ' ') s1
        return (fromIntegral n, s2)

main :: IO ()
main = do
    t <- readLn
    replicateM_ t $ do
        [n, m] <- readChar8'
        xs <- foldl' (.|.) 0 <$> replicateM m ((!! 2) <$> readChar8')
        print $ fromIntegral @Int @Integer xs * ((1 `shiftL` (n-1)) `mod` 1000000007) `mod` 1000000007

{-# LANGUAGE DeriveTraversable #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -funfolding-use-threshold=16 #-}
{-# OPTIONS_GHC -O2 #-}
{-# OPTIONS_GHC -optc-O3 #-}

module Main where

import           Control.Exception              ( Exception )
import           Control.Monad                  ( replicateM_, foldM_, replicateM )
import           Data.Array.Unboxed             ( (!)
                                                , (//)
                                                , UArray
                                                , listArray
                                                )
import qualified Data.ByteString.Char8         as C
import           Data.List                      ( foldl'
                                                , mapAccumL
                                                , unfoldr
                                                )
import           Prelude                 hiding ( replicate )
import Text.Printf (printf)
import Data.Functor (($>))
import Data.Bits ((.|.), shiftL)

-- arrange :: [a] -> Int -> [[a]]
-- arrange xs n = mapM (const xs) [1 .. n]

-- data Tree a = Null | Branch a (Tree a) (Tree a)
--   deriving (Show, Eq, Functor)

-- makeBaseFunctor ''Tree

-- x :: Tree Int
-- x = Branch 1 (Branch 2 Null Null) (Branch 3 Null Null)

-- y :: Tree Int -> Int
-- y = cata $ \case
--     NullF         -> 0
--     BranchF x a b -> x + a + b

-- >>> y x
-- 6

-- z :: Tree Int -> Int
-- z = para $ \case
--     NullF                     -> 0
--     BranchF x (x1, a) (x2, b) -> x + a + b + y x1 + y x2

-- >>> z x
-- 11

-- quicksort :: Ord a => [a] -> [a]
-- quicksort = hylo merge split  where
--     split []       = NullF
--     split (x : xs) = let (l, r) = partition (< x) xs in BranchF x l r

--     merge NullF           = []
--     merge (BranchF x l r) = l ++ [x] ++ r

-- >>> quicksort ([5,4,6,7,8,6,4,2])
-- [2,4,4,5,6,6,7,8]

-- fibSeq :: [Int]
-- fibSeq = futu phi Nil
--   where
--     phi Nil                    = Cons 0 (Pure (Cons 0 Nil))
--     phi x@(Cons _ Nil        ) = Cons 1 (Pure (Cons 1 (Cons 0 Nil)))
--     phi t@(Cons x (Cons y xs)) = Cons (x + y) (Pure (Cons (x + y) (Cons x Nil)))

-- >>> take 20 fibSeq
-- [0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181]

-- f1 :: [Int] -> Int
-- f1 = flip runReader 0 . cataA phi
--   where
--     phi Nil        = return 0
--     phi (Cons x t) = do
--         n <- ask
--         if n >= 10 then return 0 else (x +) <$> local succ t

-- f2 :: [Int]
-- f2 = apo phi 1
--   where
--     phi n | n < 100   = Cons (n * 2) (Right (n + 1))
--           | otherwise = Cons (n * 2) (Left [1, 2, 3])

-- >>> f1 fibSeq
-- 88

-- >>> f2
-- [2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,80,82,84,86,88,90,92,94,96,98,100,102,104,106,108,110,112,114,116,118,120,122,124,126,128,130,132,134,136,138,140,142,144,146,148,150,152,154,156,158,160,162,164,166,168,170,172,174,176,178,180,182,184,186,188,190,192,194,196,198]

-- urlParser :: Parser String
-- urlParser = argument str (metavar "URL")

-- segmented :: Int -> Int -> [(Int, Int)]
-- segmented total blocksize = (id &&& (min (total - 1) . (+ (blocksize - 1)))) <$> takeWhile (< total) [0, blocksize ..]

-- main :: IO ()
-- main = do
--     manager <- newManager tlsManagerSettings
--     url     <- execParser opts
--     req     <- parseRequest url
--     res     <- httpNoBody req manager
--     let len = maybe 0 fst (readInt =<< (lookup "Content-Length" (requestHeaders req) <|> lookup "content-length" (responseHeaders res)))
--     if len == 0
--         then do
--             res <- httpLbs req manager
--             print $ responseStatus res
--             print $ responseBody res
--         else do
--             pool <- createPool (pure ()) (const (pure ())) 2 0.5 5
--             mapConcurrently_
--                 (\(s, e) -> withResource pool $ \_ -> do
--                     res <- httpLbs (req { requestHeaders = ("Range", BS.pack $ formatToString ("bytes=" % int % "-" % int) s e) : requestHeaders req }) manager
--                     print $ responseStatus res
--                     -- print $ responseBody res
--                 )
--                 (segmented len tenMegabytes)
--   where
--     opts         = info urlParser fullDesc
--     tenMegabytes = 10485760

data Break = Break
    deriving Show

instance Exception Break

readChar8 :: IO [Int]
readChar8 = map parse . C.words <$> C.getLine where parse s = let Just (n, _) = C.readInt s in n

readChar8' :: IO [Int]
readChar8' = parse <$> C.getLine
  where
    parse = unfoldr go
    go s = do
        (n, s1) <- C.readInt s
        let s2 = C.dropWhile (== ' ') s1
        return (fromIntegral n, s2)

main :: IO ()
main = do
    t <- readLn
    replicateM_ t $ do
        [n, m] <- readChar8'
        xs <- foldl' (.|.) 0 <$> replicateM m ((!! 2) <$> readChar8')
        print $ fromIntegral @Int @Integer xs * (1 `shiftL` (n-1))

{-# LANGUAGE DeriveTraversable #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -funfolding-use-threshold=16 #-}
{-# OPTIONS_GHC -O2 #-}
{-# OPTIONS_GHC -optc-O3 #-}

module Main where

import           Control.Exception              ( Exception )
import           Control.Monad                  ( replicateM_, foldM_, replicateM )
import           Data.Array.Unboxed             ( (!)
                                                , (//)
                                                , UArray
                                                , listArray
                                                )
import qualified Data.ByteString.Char8         as C
import           Data.List                      ( foldl'
                                                , mapAccumL
                                                , unfoldr
                                                )
import           Prelude                 hiding ( replicate )
import Text.Printf (printf)
import Data.Functor (($>))
import Data.Bits ((.|.), shiftL)

-- arrange :: [a] -> Int -> [[a]]
-- arrange xs n = mapM (const xs) [1 .. n]

-- data Tree a = Null | Branch a (Tree a) (Tree a)
--   deriving (Show, Eq, Functor)

-- makeBaseFunctor ''Tree

-- x :: Tree Int
-- x = Branch 1 (Branch 2 Null Null) (Branch 3 Null Null)

-- y :: Tree Int -> Int
-- y = cata $ \case
--     NullF         -> 0
--     BranchF x a b -> x + a + b

-- >>> y x
-- 6

-- z :: Tree Int -> Int
-- z = para $ \case
--     NullF                     -> 0
--     BranchF x (x1, a) (x2, b) -> x + a + b + y x1 + y x2

-- >>> z x
-- 11

-- quicksort :: Ord a => [a] -> [a]
-- quicksort = hylo merge split  where
--     split []       = NullF
--     split (x : xs) = let (l, r) = partition (< x) xs in BranchF x l r

--     merge NullF           = []
--     merge (BranchF x l r) = l ++ [x] ++ r

-- >>> quicksort ([5,4,6,7,8,6,4,2])
-- [2,4,4,5,6,6,7,8]

-- fibSeq :: [Int]
-- fibSeq = futu phi Nil
--   where
--     phi Nil                    = Cons 0 (Pure (Cons 0 Nil))
--     phi x@(Cons _ Nil        ) = Cons 1 (Pure (Cons 1 (Cons 0 Nil)))
--     phi t@(Cons x (Cons y xs)) = Cons (x + y) (Pure (Cons (x + y) (Cons x Nil)))

-- >>> take 20 fibSeq
-- [0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181]

-- f1 :: [Int] -> Int
-- f1 = flip runReader 0 . cataA phi
--   where
--     phi Nil        = return 0
--     phi (Cons x t) = do
--         n <- ask
--         if n >= 10 then return 0 else (x +) <$> local succ t

-- f2 :: [Int]
-- f2 = apo phi 1
--   where
--     phi n | n < 100   = Cons (n * 2) (Right (n + 1))
--           | otherwise = Cons (n * 2) (Left [1, 2, 3])

-- >>> f1 fibSeq
-- 88

-- >>> f2
-- [2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,80,82,84,86,88,90,92,94,96,98,100,102,104,106,108,110,112,114,116,118,120,122,124,126,128,130,132,134,136,138,140,142,144,146,148,150,152,154,156,158,160,162,164,166,168,170,172,174,176,178,180,182,184,186,188,190,192,194,196,198]

-- urlParser :: Parser String
-- urlParser = argument str (metavar "URL")

-- segmented :: Int -> Int -> [(Int, Int)]
-- segmented total blocksize = (id &&& (min (total - 1) . (+ (blocksize - 1)))) <$> takeWhile (< total) [0, blocksize ..]

-- main :: IO ()
-- main = do
--     manager <- newManager tlsManagerSettings
--     url     <- execParser opts
--     req     <- parseRequest url
--     res     <- httpNoBody req manager
--     let len = maybe 0 fst (readInt =<< (lookup "Content-Length" (requestHeaders req) <|> lookup "content-length" (responseHeaders res)))
--     if len == 0
--         then do
--             res <- httpLbs req manager
--             print $ responseStatus res
--             print $ responseBody res
--         else do
--             pool <- createPool (pure ()) (const (pure ())) 2 0.5 5
--             mapConcurrently_
--                 (\(s, e) -> withResource pool $ \_ -> do
--                     res <- httpLbs (req { requestHeaders = ("Range", BS.pack $ formatToString ("bytes=" % int % "-" % int) s e) : requestHeaders req }) manager
--                     print $ responseStatus res
--                     -- print $ responseBody res
--                 )
--                 (segmented len tenMegabytes)
--   where
--     opts         = info urlParser fullDesc
--     tenMegabytes = 10485760

data Break = Break
    deriving Show

instance Exception Break

readChar8 :: IO [Int]
readChar8 = map parse . C.words <$> C.getLine where parse s = let Just (n, _) = C.readInt s in n

readChar8' :: IO [Int]
readChar8' = parse <$> C.getLine
  where
    parse = unfoldr go
    go s = do
        (n, s1) <- C.readInt s
        let s2 = C.dropWhile (== ' ') s1
        return (fromIntegral n, s2)

main :: IO ()
main = do
    t <- readLn
    replicateM_ t $ do
        [n, m] <- readChar8'
        xs <- foldl' (.|.) 0 <$> replicateM m ((!! 2) <$> readChar8')
        print $ xs * (1 `shiftL` (n-1))


Positive integer $$$x$$$ is called divisor of positive integer $$$y$$$, if $$$y$$$ is divisible by $$$x$$$ without remainder. For example, $$$1$$$ is a divisor of $$$7$$$ and $$$3$$$ is not divisor of $$$8$$$.We gave you an integer $$$d$$$ and asked you to find the smallest positive integer $$$a$$$, such that  $$$a$$$ has at least $$$4$$$ divisors;  difference between any two divisors of $$$a$$$ is at least $$$d$$$.

The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 3000$$$) — the number of test cases. The first line of each test case contains a single integer $$$d$$$ ($$$1 \leq d \leq 10000$$$).

For each test case print one integer $$$a$$$ — the answer for this test case.

NoteIn the first test case, integer $$$6$$$ have following divisors: $$$[1, 2, 3, 6]$$$. There are $$$4$$$ of them and the difference between any two of them is at least $$$1$$$. There is no smaller integer with at least $$$4$$$ divisors.In the second test case, integer $$$15$$$ have following divisors: $$$[1, 3, 5, 15]$$$. There are $$$4$$$ of them and the difference between any two of them is at least $$$2$$$.The answer $$$12$$$ is INVALID because divisors are $$$[1, 2, 3, 4, 6, 12]$$$. And the difference between, for example, divisors $$$2$$$ and $$$3$$$ is less than $$$d=2$$$.

import Control.Monad

isPrime 2 = True
isPrime n
        | even n = False
        | n < 2 = False
        | any (\x->mod n x==0) $ takeWhile (\x->x*x<=n) [3,5..] = False
        | otherwise = True

solve x = head [i|i<-[x..],isPrime i]

printResult = do
    d <- readLn :: IO Int
    let x = solve $ d + 1
        y = solve $ x + d
    print $ x * y
main = do
    t <- readLn :: IO Int
    replicateM_ t printResult

import Data.List  (find)
import Data.Maybe (fromJust)

minus :: [Int] -> [Int] -> [Int]
minus (x:xs) (y:ys) = case compare x y of
           LT -> x : minus  xs  (y:ys)
           EQ ->     minus  xs     ys
           GT ->     minus (x:xs)  ys
minus  xs     _     = xs

merge :: [Int] -> [Int] -> [Int]
merge (x:xs) (y:ys) = case compare x y of
           LT -> x : merge  xs  (y:ys)
           EQ -> x : merge  xs     ys
           GT -> y : merge (x:xs)  ys
merge  xs     []    = xs
merge  []     ys    = ys

mergeAll :: [[Int]] -> [Int]
mergeAll = foldr (\(x : xs) -> (x : ) . merge xs) []

primes :: [Int]
primes = 2 : 3 : minus [5,7..] (mergeAll [[p*p, p*p+2*p..] | p <- tail primes])

process :: Int -> Int
process d = p * q
    where p = fromJust $ find (>= d + 1) primes
          q = fromJust $ find (>= p + d) primes

main :: IO ()
main = interact (unlines . map (show . process . (read :: String -> Int)) . tail . lines)

{-# LANGUAGE DeriveFunctor       #-}
{-# LANGUAGE GADTs               #-}
{-# LANGUAGE OverloadedStrings   #-}
{-# LANGUAGE Safe                #-}
{-# LANGUAGE Strict #-}
{-# LANGUAGE ScopedTypeVariables #-}

import           Control.Arrow              ((>>>))
import           Control.Monad              (MonadPlus (mplus), foldM_, forM_,
                                             guard, join, replicateM,
                                             replicateM_)
import qualified Control.Monad.ST.Strict    as ST
import qualified Control.Monad.State.Strict as S
import qualified Data.Array                 as A
import qualified Data.Array.MArray.Safe     as MA
import qualified Data.Array.ST.Safe         as STA
import qualified Data.Array.Unboxed         as UA
import           Data.Bits
import qualified Data.ByteString.Char8      as B8
import           Data.Char
import           Data.Function              (on)
import           Data.Functor               ((<&>))
import           Data.IORef                 (modifyIORef, newIORef, readIORef)
import           Data.Int
import qualified Data.IntMap                as IM
import           Data.List                  (elemIndices, find, findIndices,
                                             intersect, isPrefixOf, nub, sort,
                                             sortOn)
import qualified Data.Map                   as M
import           Data.Maybe                 (fromJust, fromMaybe, isJust)
import qualified Data.Set                   as S
import           Data.Traversable           (forM)
import           GHC.IO.Handle              (hDuplicateTo)
import           System.IO                  (IOMode (ReadMode, WriteMode),
                                             openFile, stdin, stdout)
import           Text.Printf                (printf)

-- import Debug.Trace (trace)
-- debug = flip trace

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

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

isPrime :: Int64 -> Bool
isPrime x = all (\d -> x `mod` d /= 0) ds
    where
        sqrtX = floor . sqrt . fromIntegral $ x
        ds = [2 .. sqrtX]

nextPrime :: Int64 -> Int64
nextPrime x = fromJust . find isPrime $ [x..]

solve :: Int64 -> Int64
solve d = x * y
    where
        x = nextPrime (d + 1)
        y = nextPrime (x + d)

main :: IO ()
main = do
    t <- B8.getLine <&> readIntB8
    replicateM_ t $ do
        dd <- B8.getLine <&> readIntegerB8
        let d :: Int64 = fromInteger dd
        let answer = solve d
        printf "%lld\n" answer

module Main where

sieve a b
    |b==[] = []
    |(head b)>a = sieve (a+1) b
    |(head b)==a = (head b):(sieve (a+1) (filter (\e->(e`mod`a)/=0) (tail b)))
    |otherwise = sieve (a+1) (filter (\e->(e`mod`a)/=0) b)

primes=sieve 2 [2..30000]

search_geq (x:xs) b
    | x>=b = x
    | otherwise = search_geq xs b

work t=p*q
    where
        p=search_geq primes $ t+1
        q=search_geq primes $ p+t

run 1 = do
    l1 <- getLine
    putStrLn $ show $ work ((read::String->Integer) l1)

run x = do
    run 1
    run (x-1)

main = do
    l1 <- getLine
    let t = (read::String->Integer) l1
    run t

import Control.Monad

isPrime 2 = True
isPrime n
        | even n = False
        | n < 2 = False
        | any (\x->mod n x==0) $ takeWhile (\x->x*x<=n) [3,5..] = False
        | otherwise = True

solve x = head [i|i<-[x..],isPrime i]

printResult = do
    d <- readLn :: IO Int
    print $ solve (d+1) * solve (1+2*d)

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

import Control.Monad

printResult = do
    d <- readLn :: IO Int
    print $ (1+d) * (1+2*d)

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


Serega and Fedor play with functions. One day they came across a very interesting function. It looks like that:  f(1, j) = a[j], 1 ≤ j ≤ n.  f(i, j) = min(f(i - 1, j), f(i - 1, j - 1)) + a[j], 2 ≤ i ≤ n, i ≤ j ≤ n. Here a is an integer array of length n.Serega and Fedya want to know what values this function takes at some points. But they don't want to calculate the values manually. So they ask you to help them.

The first line contains integer n (1 ≤ n ≤ 105) — the length of array a. The next line contains n integers: a[1], a[2], ..., a[n] (0 ≤ a[i] ≤ 104). The next line contains integer m (1 ≤ m ≤ 105) — the number of queries. Each of the next m lines contains two integers: xi, yi (1 ≤ xi ≤ yi ≤ n). Each line means that Fedor and Serega want to know the value of f(xi, yi).

Print m lines — the answers to the guys' queries.

{-# LANGUAGE BangPatterns #-}
import Data.Int
import Data.Maybe
import Data.Array.Unboxed
import Data.Bits
import Data.Functor
import Control.Monad
import qualified Data.ByteString.Lazy.Char8 as LB

type I = Int

data Linear = Linear !I !I deriving (Show, Eq)

type PiecewiseLinear = [(I, I, Linear)]

inter :: Linear -> Linear -> Maybe I
inter (Linear a1 b1) (Linear a2 b2)
  | a1 < a2 = Just $ (b1 - b2) `div` (a2 - a1)
  | a2 < a1 = Just $ (b2 - b1) `div` (a1 - a2)
  | otherwise = Nothing

sample :: Linear -> I -> I
sample (Linear a b) x = a * x + b

plmin :: PiecewiseLinear -> PiecewiseLinear -> PiecewiseLinear
plmin [] [] = []
plmin [] arg2@((s2@(l2, r2, f2)) : rest2)
  | l2 > r2 = plmin [] rest2
  | otherwise = arg2
plmin arg1@((s1@(l1, r1, f1)) : rest1) []
  | l1 > r1 = plmin rest1 []
  | otherwise = arg1
plmin arg1@((s1@(l1, r1, f1)) : rest1) arg2@((s2@(l2, r2, f2)) : rest2)
  | l1 > r1 = plmin rest1 arg2
  | l2 > r2 = plmin arg1 rest2
  | yl1 < yl2 && yr1 > yr2   = (l1, m, f1) : next m
  | yl2 < yl1 && yr2 > yr1   = (l1, m, f2) : next m
  | yl1 <= yl2 && yr1 <= yr2 = (l1, r, f1) : next r
  | yl2 <= yl1 && yr2 <= yr1 = (l1, r, f2) : next r
  where
    r = min r1 r2
    l = (l1 == l2 || error "l1 should be equal to l2") `seq` l1
    mm = inter f1 f2
    m = fromJust mm
    yl1 = sample f1 l1
    yl2 = sample f2 l1
    yr1 = sample f1 r
    yr2 = sample f2 r
    next x = plmin ((x+1, r1, f1):rest1) ((x+1, r2, f2):rest2)

refine :: PiecewiseLinear -> PiecewiseLinear
refine [] = []
refine [x] = [x]
refine ((l1, r1, f1) : (l2, r2, f2) : rest)
  | f1 == f2 = refine $ (l1, r2, f1) : rest
  | otherwise = (l1, r1, f1) : (refine $ (l2, r2, f2) : rest)

plmin' :: PiecewiseLinear -> PiecewiseLinear -> PiecewiseLinear
plmin' arg1 arg2 = refine $ plmin arg1 arg2

f1 = [(0, 3, Linear 3 0), (4, 10, Linear 0 9)]
f2 = [(0, 2, Linear (-2) 4), (3, 5, Linear 4 (-8)), (6,6, Linear 0 12), (7, 10, Linear (-1) 18)]

data InTree a = Leaf !Int !a | Node !Int !Int !a !(InTree a) !(InTree a) deriving Show

instance Functor InTree where
  fmap f (Leaf x a) = Leaf x (f a)
  fmap f (Node l r a tl tr) = Node l r (f a) (f <$> tl) (f <$> tr)

getValue :: InTree a -> a
getValue (Leaf _ x) = x
getValue (Node _ _ x _ _) = x

buildWith :: (a -> a -> a) -> [a] -> InTree a
buildWith f xxs = go 1 xxs
  where
    go i [x] = {-# SCC "go" #-} Leaf i x
    go i xs = {-# SCC "go" #-} Node i (i + len - 1) (f (getValue leftChild) (getValue rightChild)) leftChild rightChild
      where
        len = length xs
        (left, right) = splitAt (len `shiftR` 1) xs

        leftChild = go i left
        rightChild = go (i + len `shiftR` 1) right

queryWith :: b -> (b -> b -> b) -> (a -> b) -> Int -> Int -> InTree a -> b
queryWith def combine qNode l r = queryWith'
  where
    queryWith' (Leaf n a)
      | l <= n && n <= r = qNode a
      | l > n || n > r = def
    queryWith' (Node nL nR a tl tr)
      | l > nR || r < nL = def
      | l > nL || r < nR  = combine (queryWith' tl) (queryWith' tr)
      | l <= nL && r >= nR = qNode a

scanl' f a (x:xs) = let x' = f a x in x' `seq` (a : scanl' f x' xs)
scanl' _ a [] = [a]

makeLinear :: Int -> I -> I -> Linear
makeLinear k a s = Linear a ((fromIntegral k) * a - s)

toSamplable :: PiecewiseLinear -> Array Int (I, I, Linear)
toSamplable pl = array (1, length pl) (zip [1..] pl)

samplePL :: I -> Array Int (I, I, Linear) -> I
samplePL x a = go l r
  where
    (l,r) = bounds a
    go l r
      | l == r = sample lf x
      | aml > x = go l (m-1)
      | amr < x = go (m+1) r
      | aml <= x && amr >= x = sample amf x
      where
        m = (l + r) `shiftR` 1
        (aml, amr, amf) = a ! m
        (_,_,lf) = a ! l

{-# NOINLINE solve #-}
solve :: Array Int I -> InTree (Array Int (I, I, Linear)) -> IO ()
solve s t = do
  line <- getLine
  let [i,j] = map (fst . fromJust . LB.readInt) (LB.words $ LB.pack line) :: [Int]
  LB.putStrLn $ LB.pack $ show $ (s ! j) + queryWith 2000000000 min (samplePL (fromIntegral $ i - j)) (j - i + 1) j t

main = do
  line1 <- getLine
  line2 <- getLine
  let !xs = map (fromIntegral . fst . fromJust . LB.readInt) $ LB.words $ LB.pack line2 :: [I]
      !ss = tail $ scanl' (+) 0 xs
      !ssa = array (1,length xs) (zip [1..] ss) :: Array Int I
      !ls = map ( \f -> [(-100000, 100000, f)]) $ zipWith3 makeLinear [1..] xs ss
      !t = toSamplable <$> buildWith plmin' ls :: InTree (Array Int (I, I, Linear))
  line3 <- getLine
  let m = read line3 :: Int
  replicateM_ m (solve ssa t)

{-# LANGUAGE UnboxedTuples #-}
import Data.Int
import Data.Maybe
import Data.Array.Unboxed
import Data.Bits
import Data.Functor
import Control.Monad
import qualified Data.ByteString.Lazy.Char8 as LB

type I = Int

data Linear = Linear !I !I deriving (Show, Eq)

type PiecewiseLinear = [(I, I, Linear)]

inter :: Linear -> Linear -> Maybe I
inter (Linear a1 b1) (Linear a2 b2)
  | a1 < a2 = Just $ (b1 - b2) `div` (a2 - a1)
  | a2 < a1 = Just $ (b2 - b1) `div` (a1 - a2)
  | otherwise = Nothing

sample :: Linear -> I -> I
sample (Linear a b) x = a * x + b

plmin :: PiecewiseLinear -> PiecewiseLinear -> PiecewiseLinear
plmin [] [] = []
plmin [] arg2@((s2@(l2, r2, f2)) : rest2)
  | l2 > r2 = plmin [] rest2
  | otherwise = arg2
plmin arg1@((s1@(l1, r1, f1)) : rest1) []
  | l1 > r1 = plmin rest1 []
  | otherwise = arg1
plmin arg1@((s1@(l1, r1, f1)) : rest1) arg2@((s2@(l2, r2, f2)) : rest2)
  | l1 > r1 = plmin rest1 arg2
  | l2 > r2 = plmin arg1 rest2
  | yl1 < yl2 && yr1 > yr2   = (l1, m, f1) : next m
  | yl2 < yl1 && yr2 > yr1   = (l1, m, f2) : next m
  | yl1 <= yl2 && yr1 <= yr2 = (l1, r, f1) : next r
  | yl2 <= yl1 && yr2 <= yr1 = (l1, r, f2) : next r
  where
    r = min r1 r2
    l = (l1 == l2 || error "l1 should be equal to l2") `seq` l1
    mm = inter f1 f2
    m = fromJust mm
    yl1 = sample f1 l1
    yl2 = sample f2 l1
    yr1 = sample f1 r
    yr2 = sample f2 r
    next x = plmin ((x+1, r1, f1):rest1) ((x+1, r2, f2):rest2)

refine :: PiecewiseLinear -> PiecewiseLinear
refine [] = []
refine [x] = [x]
refine ((l1, r1, f1) : (l2, r2, f2) : rest)
  | f1 == f2 = refine $ (l1, r2, f1) : rest
  | otherwise = (l1, r1, f1) : (refine $ (l2, r2, f2) : rest)

plmin' :: PiecewiseLinear -> PiecewiseLinear -> PiecewiseLinear
plmin' arg1 arg2 = refine $ plmin arg1 arg2

f1 = [(0, 3, Linear 3 0), (4, 10, Linear 0 9)]
f2 = [(0, 2, Linear (-2) 4), (3, 5, Linear 4 (-8)), (6,6, Linear 0 12), (7, 10, Linear (-1) 18)]

data InTree a = Leaf !Int !a | Node !Int !Int !a !(InTree a) !(InTree a) deriving Show

instance Functor InTree where
  fmap f (Leaf x a) = Leaf x (f a)
  fmap f (Node l r a tl tr) = Node l r (f a) (f <$> tl) (f <$> tr)

getValue :: InTree a -> a
getValue (Leaf _ x) = x
getValue (Node _ _ x _ _) = x

buildWith :: (a -> a -> a) -> [a] -> InTree a
buildWith f xxs = go 1 xxs
  where
    go i [x] = Leaf i x
    go i xs = Node i (i + len - 1) (f (getValue leftChild) (getValue rightChild)) leftChild rightChild
      where
        len = length xs
        (left, right) = splitAt (len `shiftR` 1) xs

        leftChild = go i left
        rightChild = go (i + len `shiftR` 1) right

queryWith :: b -> (b -> b -> b) -> (a -> b) -> Int -> Int -> InTree a -> b
queryWith def combine qNode l r = queryWith'
  where
    queryWith' (Leaf n a)
      | l <= n && n <= r = qNode a
      | l > n || n > r = def
    queryWith' (Node nL nR a tl tr)
      | l > nR || r < nL = def
      | l > nL || r < nR  = combine (queryWith' tl) (queryWith' tr)
      | l <= nL && r >= nR = qNode a

scanl' f a (x:xs) = let x' = f a x in x' `seq` (a : scanl' f x' xs)
scanl' _ a [] = [a]

makeLinear :: Int -> I -> I -> Linear
makeLinear k a s = Linear a ((fromIntegral k) * a - s)

toSamplable :: PiecewiseLinear -> Array Int (I, I, Linear)
toSamplable pl = array (1, length pl) (zip [1..] pl)

samplePL :: I -> Array Int (I, I, Linear) -> I
samplePL x a = go l r
  where
    (l,r) = bounds a
    go l r
      | l == r = sample lf x
      | aml > x = go l (m-1)
      | amr < x = go (m+1) r
      | aml <= x && amr >= x = sample amf x
      where
        m = (l + r) `shiftR` 1
        (aml, amr, amf) = a ! m
        (_,_,lf) = a ! l

{-# NOINLINE solve #-}
solve :: Array Int I -> InTree (Array Int (I, I, Linear)) -> IO ()
solve s t = do
  line <- getLine
  let [i,j] = map (fst . fromJust . LB.readInt) (LB.words $ LB.pack line) :: [Int]
  LB.putStr $ LB.pack $ show $ (s ! j) + queryWith 2000000000 min (samplePL (fromIntegral $ i - j)) (j - i + 1) j t

main = do
  line1 <- getLine
  line2 <- getLine
  let xs = map (fromIntegral . fst . fromJust . LB.readInt) $ LB.words $ LB.pack line2 :: [I]
      ss = tail $ scanl' (+) 0 xs
      ssa = array (1,length xs) (zip [1..] ss)
      ls = map ( \f -> [(-100000, 100000, f)]) $ zipWith3 makeLinear [1..] xs ss
      t = toSamplable <$> buildWith plmin' ls
  line3 <- getLine
  let m = read line3 :: Int
  replicateM_ m (solve ssa t)


Andrew was very excited to participate in Olympiad of Metropolises. Days flew by quickly, and Andrew is already at the airport, ready to go home. He has $$$n$$$ rubles left, and would like to exchange them to euro and dollar bills. Andrew can mix dollar bills and euro bills in whatever way he wants. The price of one dollar is $$$d$$$ rubles, and one euro costs $$$e$$$ rubles.Recall that there exist the following dollar bills: $$$1$$$, $$$2$$$, $$$5$$$, $$$10$$$, $$$20$$$, $$$50$$$, $$$100$$$, and the following euro bills — $$$5$$$, $$$10$$$, $$$20$$$, $$$50$$$, $$$100$$$, $$$200$$$ (note that, in this problem we do not consider the $$$500$$$ euro bill, it is hard to find such bills in the currency exchange points). Andrew can buy any combination of bills, and his goal is to minimize the total number of rubles he will have after the exchange.Help him — write a program that given integers $$$n$$$, $$$e$$$ and $$$d$$$, finds the minimum number of rubles Andrew can get after buying dollar and euro bills.

The first line of the input contains one integer $$$n$$$ ($$$1 \leq n \leq 10^8$$$) — the initial sum in rubles Andrew has.  The second line of the input contains one integer $$$d$$$ ($$$30 \leq d \leq 100$$$) — the price of one dollar in rubles.  The third line of the input contains integer $$$e$$$ ($$$30 \leq e \leq 100$$$) — the price of one euro in rubles.

Output one integer — the minimum number of rubles Andrew can have after buying dollar and euro bills optimally.

NoteIn the first example, we can buy just $$$1$$$ dollar because there is no $$$1$$$ euro bill.In the second example, optimal exchange is to buy $$$5$$$ euro and $$$1$$$ dollar.In the third example, optimal exchange is to buy $$$10$$$ dollars in one bill.

readIntLn :: IO Int
readIntLn = read `fmap` getLine
main :: IO ()
main = do
    n <- readIntLn
    a <- readIntLn
    b <- (5*) `fmap `readIntLn
    print $ foldr min (n `mod` b) $ map ((`mod` b) . (n-) . (a*)) [1 .. n `div` a]


Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the temple and read the string aloud. However, nothing happened. Then Asterix supposed that a password is some substring t of the string s.Prefix supposed that the substring t is the beginning of the string s; Suffix supposed that the substring t should be the end of the string s; and Obelix supposed that t should be located somewhere inside the string s, that is, t is neither its beginning, nor its end.Asterix chose the substring t so as to please all his companions. Besides, from all acceptable variants Asterix chose the longest one (as Asterix loves long strings). When Asterix read the substring t aloud, the temple doors opened. You know the string s. Find the substring t or determine that such substring does not exist and all that's been written above is just a nice legend.

You are given the string s whose length can vary from 1 to 106 (inclusive), consisting of small Latin letters.

Print the string t. If a suitable t string does not exist, then print "Just a legend" without the quotes.

import Data.Maybe (fromMaybe, listToMaybe)

import Control.Monad (foldM_)
import Data.Array.MArray (newArray, readArray, writeArray)
import Data.Array.ST (runSTUArray)
import Data.Array.Unboxed -- (UArray, (!), listArray, elems)

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

zFunction :: String -> UArray Int Int
zFunction s  =  runSTUArray $ do
    z  <-  newArray (1, n) 0
    writeArray z 1 n
    foldM_ (iter z) (1, 1) [2..n]
    return z
  where
    n   =  length s
    s'  =  listArray (1, n) s :: UArray Int Char
    iter z (l, r) i  =  do
        zil  <-  readArray z (i - l + 1)
        let z0  =  (i > r) ? 0 $ min (r - i + 1) zil
        let zi  =  head $ dropWhile (\j -> i + j <= n && s' ! (j + 1) == s' ! (i + j)) [z0..]
        writeArray z i zi
        return $ (i + zi - 1 > r) ? (i, i + zi - 1) $ (l, r)

solve :: String -> Maybe String
solve s
  | n <= 2  =  Nothing
  | otherwise  =  listToMaybe [take (z ! i) s | i <- [2..n], (z ! i) <= mx, i + z ! i == n + 1]
  where
    n   =  length s
    z   =  zFunction s
    z'  =  zFunction $ init s
    mx  =  maximum $ tail $ elems z'

main :: IO ()
main  =  getLine >>= putStrLn . fromMaybe "Just a legend" . solve

{-# LANGUAGE BangPatterns #-}
{-# OPTIONS_GHC -O3 -optc-O3 #-}
import Data.Word

import qualified Data.ByteString as B

data Item = Item { next :: Item, prefix :: Item, ch :: Word8, k :: Int } | NilItem deriving (Eq)

find i c =
	let i' = prefix i in
	if i' == NilItem || ch i == c then i else find i' c

build ind !i s
	| s == B.empty = []
	| otherwise =
		Item (head is) i'' (B.head $ B.tail s) ind : is
		where
			i' = find i (B.head s)
			i'' = if ind /= 1 && ch i' == B.head s then next i' else i'
			is = build (ind + 1) i'' (B.tail s)

main = do
	s1 <- B.getLine

	let	s = B.init s1

	let	i = Item (head is) NilItem (B.head s) 0
		is = build 1 i s
		ps = map (\i -> k $ prefix i) is

		n = B.length s

		p = ps !! (n-1)

	if p == 0
	then putStrLn "Just a legend"
	else
		let ps' = filter (== p) (init ps) in
			if ps' /= []
			then B.putStrLn $ B.take (head ps') s
			else
				let p' = ps !! (p - 1) in
				if p' == 0
				then putStrLn "Just a legend"
				else B.putStrLn $ B.take p' s

{-# LANGUAGE BangPatterns #-}
{-# OPTIONS_GHC -O3 -optc-O3 #-}
import Data.Word

import qualified Data.ByteString as B

data Item = Item { next :: Item, prefix :: Item, ch :: Word8, k :: Int } | NilItem deriving (Eq)

build ind !i s
	| s == B.empty = []
	| otherwise =
		Item (head is) i'' (B.head $ B.tail s) ind : is
		where
			c = B.head s
			i' = find i
			i'' = if ind /= 1 && ch i' == c then next i' else i'
			is = build (ind + 1) i'' (B.tail s)

			find i
				| i' == NilItem || ch i == c = i
				| otherwise = find i'
				where i' = prefix i

main = do
	s1 <- B.getLine

	let	s = B.init s1

	let	i = Item (head is) NilItem (B.head s) 0
		is = build 1 i s
		ps = map (\i -> k $ prefix i) is

		n = B.length s

		p = ps !! (n-1)

	if p == 0
	then putStrLn "Just a legend"
	else
		let ps' = filter (== p) (init ps) in
			if ps' /= []
			then B.putStrLn $ B.take (head ps') s
			else
				let p' = ps !! (p - 1) in
				if p' == 0
				then putStrLn "Just a legend"
				else B.putStrLn $ B.take p' s

{-# LANGUAGE BangPatterns #-}
{-# OPTIONS_GHC -O3 -optc-O3 #-}
import Data.Word

import qualified Data.ByteString as B

data Item = Item { next :: Item, prefix :: Item, ch :: Word8, k :: Int } | NilItem deriving (Eq)

find i c =
	let i' = prefix i in
	if i' == NilItem
	then i
	else if ch i == c
		then i
		else find i' c

build :: Int -> Item -> B.ByteString -> [Item]
-- build ind i [] = []
build ind !i s =
	if s == B.empty then [] else
	let	i' = find i (B.head s)
		i'' = if ind /= 1 && ch i' == B.head s then next i' else i'
		is = build (ind + 1) i'' (B.tail s)
	in Item (head is) i'' (B.head $ B.tail s) ind : is

main = do
	s1 <- B.getLine

	let	s = B.init s1

	let	i = Item (head is) NilItem (B.head s) 0
		is = build 1 i s
		ps = map (\i -> k $ prefix i) is

		n = B.length s

		p = ps !! (n-1)

	if p == 0
	then putStrLn "Just a legend"
	else
		let ps' = filter (== p) (init ps) in
			if ps' /= []
			then B.putStrLn $ B.take (head ps') s
			else
				let p' = ps !! (p - 1) in
				if p' == 0
				then putStrLn "Just a legend"
				else B.putStrLn $ B.take p' s

{-# LANGUAGE BangPatterns #-}
{-# OPTIONS_GHC -O3 -optc-O3 #-}
data Item = Item { next :: Item, prefix :: Item, ch :: Char, k :: Int } | NilItem deriving (Eq)

find i c =
	let i' = prefix i in
	if i' == NilItem
	then i
	else if ch i == c
		then i
		else find i' c

build ind i "" = []
build ind !i !s =
	let	i' = find i (head s)
		i'' = if ind /= 1 && ch i' == head s then next i' else i'
		is = build (ind + 1) i'' (tail s)
	in Item (head is) i'' (head $ tail s) ind : is

main = do
	s <- getLine

	let	i = Item (head is) NilItem (head s) 0
		is = build 1 i s
		ps = map (\i -> k $ prefix i) is

		n = length s

		p = ps !! (n-1)

	if p == 0
	then putStrLn "Just a legend"
	else
		let ps' = filter (== p) (init ps) in
			if ps' /= []
			then putStrLn $ take (head ps') s
			else
				let p' = ps !! (p - 1) in
				if p' == 0
				then putStrLn "Just a legend"
				else putStrLn $ take p' s

{-# LANGUAGE BangPatterns #-}
{-# OPTIONS_GHC -O3 -optc-O3 #-}
import Data.Word

import qualified Data.ByteString as B

data Item = Item { next :: Item, prefix :: Item, ch :: Word8, k :: Int } | NilItem deriving (Eq)

build ind !i s
	| s == B.empty = []
	| otherwise =
		Item (head is) i'' (B.head $ B.tail s) ind : is
		where
			c = B.head s
			i' = find i
			i'' = if ind /= 1 && ch i' == c then next i' else i'
			is = build (ind + 1) i'' (B.tail s)

			find !i
				| i' == NilItem || ch i == c = i
				| otherwise = find i'
				where i' = prefix i

main = do
	s1 <- B.getLine

	let	s = B.init s1

	let	i = Item (head is) NilItem (B.head s) 0
		is = build 1 i s
		ps = map (\i -> k $ prefix i) is

		n = B.length s

		p = ps !! (n-1)

	if p == 0
	then putStrLn "Just a legend"
	else
		let ps' = filter (== p) (init ps) in
			if ps' /= []
			then B.putStrLn $ B.take (head ps') s
			else
				let p' = ps !! (p - 1) in
				if p' == 0
				then putStrLn "Just a legend"
				else B.putStrLn $ B.take p' s

{-# LANGUAGE BangPatterns #-}
{-# OPTIONS_GHC -O3 -optc-O3 #-}
data Item = Item { next :: Item, prefix :: Item, ch :: Char, k :: Int } | NilItem deriving (Eq)

find i c =
	let i' = prefix i in
	if i' == NilItem
	then i
	else if ch i == c
		then i
		else find i' c

build ind i "" = []
build ind !i s =
	let	i' = find i (head s)
		i'' = if ind /= 1 && ch i' == head s then next i' else i'
		is = build (ind + 1) i'' (tail s)
	in Item (head is) i'' (head $ tail s) ind : is

main = do
	s <- getLine

	let	i = Item (head is) NilItem (head s) 0
		is = build 1 i s
		ps = map (\i -> k $ prefix i) is

		n = length s

		p = ps !! (n-1)

	if p == 0
	then putStrLn "Just a legend"
	else
		let ps' = filter (== p) (init ps) in
			if ps' /= []
			then putStrLn $ take (head ps') s
			else
				let p' = ps !! (p - 1) in
				if p' == 0
				then putStrLn "Just a legend"
				else putStrLn $ take p' s

import Control.Applicative ((<$>))
import Data.List (mapAccumL)
import Data.Array (Array, listArray, elems, (!))
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as C8

zfunc :: Eq a => [a] -> [Int]
zfunc a = elems out
    where
    n = length a :: Int
    mkArray :: [a] -> Array Int a
    mkArray = listArray (0, n - 1)

    arr = mkArray a
    out = mkArray . (n:) . snd $ mapAccumL loop (0, 0) [1..] :: Array Int Int

    loop :: (Int, Int) -> Int -> ((Int, Int), Int)
    loop (l, r) i
        | r < i + 1 = ((i, r'), r' - i)
        | i + out ! (i - l) < r = ((l, r), out ! (i - l))
        | otherwise = ((i, r''), r'' - i)
        where
        next = head . dropWhile (\j -> j < n && arr ! j == arr ! (j - i))
        [r', r''] = map next [[i..], [r..]] :: [Int]

solve :: String -> String
solve [_] = "Just a legend"
solve line = if len /= 0 then take len line else "Just a legend"
    where
    n = length line :: Int
    a = tail . zip [0..] . zfunc $ line :: [(Int, Int)]

    sub = maximum $ map f a :: Int -- longest *strict* substring
        where f (i, k) = if i + k == n then k - 1 else k

    len = maximum $ map f a :: Int
        where f (i, k) = if i + k /= n || sub < k then 0 else k

main = C8.pack . solve . C8.unpack . C8.init <$> B.getLine >>= C8.putStrLn

import Control.Applicative ((<$>))
import Data.List (mapAccumL)
import Data.Array (Array, listArray, elems, (!))

zfunc :: Eq a => [a] -> [Int]
zfunc a = elems out
    where
    n = length a :: Int
    mkArray :: [a] -> Array Int a
    mkArray = listArray (0, n - 1)

    arr = mkArray a
    out = mkArray . (n:) . snd $ mapAccumL loop (0, 0) [1..] :: Array Int Int

    loop :: (Int, Int) -> Int -> ((Int, Int), Int)
    loop (l, r) i
        | r < i + 1 = ((i, r'), r' - i)
        | i + out ! (i - l) < r = ((l, r), out ! (i - l))
        | otherwise = ((i, r''), r'' - i)
        where
        next = head . dropWhile (\j -> j < n && arr ! j == arr ! (j - i))
        [r', r''] = map next [[i..], [r..]] :: [Int]

solve :: String -> String
solve [_] = "Just a legend"
solve line = if len /= 0 then take len line else "Just a legend"
    where
    n = length line :: Int
    a = tail . zip [0..] . zfunc $ line :: [(Int, Int)]

    sub = maximum $ map f a :: Int -- longest *strict* substring
        where f (i, k) = if i + k == n then k - 1 else k

    len = maximum $ map f a :: Int
        where f (i, k) = if i + k /= n || sub < k then 0 else k

main = solve <$> getLine >>= putStrLn

{-# LANGUAGE BangPatterns #-}
{-# OPTIONS_GHC -O3 -optc-O3 #-}
import Data.Word

import qualified Data.ByteString as B

data Item = Item { next :: Item, prefix :: Item, ch :: Word8, k :: Int } | NilItem deriving (Eq)

find i c =
	let i' = prefix i in
	if i' == NilItem
	then i
	else if ch i == c
		then i
		else find i' c

build :: Int -> Item -> B.ByteString -> [Item]
-- build ind i [] = []
build ind !i s =
	if s == B.empty then [] else
	let	i' = find i (B.head s)
		i'' = if ind /= 1 && ch i' == B.head s then next i' else i'
		is = build (ind + 1) i'' (B.tail s)
	in Item (head is) i'' (B.head $ B.tail s) ind : is

main = do
	s <- B.getLine

	let	i = Item (head is) NilItem (B.head s) 0
		is = build 1 i s
		ps = map (\i -> k $ prefix i) is

		n = B.length s

		p = ps !! (n-1)

	if p == 0
	then putStrLn "Just a legend"
	else
		let ps' = filter (== p) (init ps) in
			if ps' /= []
			then B.putStrLn $ B.take (head ps') s
			else
				let p' = ps !! (p - 1) in
				if p' == 0
				then putStrLn "Just a legend"
				else B.putStrLn $ B.take p' s

{-# LANGUAGE BangPatterns, MagicHash #-}
{-# OPTIONS_GHC -O2 -optc-O2 -funbox-strict-fields #-}
import Data.Word

import qualified Data.ByteString as B

data Item = Item { next :: Item, prefix :: !Item, ch :: Word8, k :: !Int } | NilItem deriving (Eq)

find i c =
	let i' = prefix i in
	if i' == NilItem
	then i
	else if ch i == c
		then i
		else find i' c

build ind !i s =
	let	i' = find i (B.head s)
		i'' = if ind /= 1 && ch i' == B.head s then next i' else i'
		is = build (ind + 1) i'' (B.tail s)
	in Item (head is) i'' (B.head $ B.tail s) ind : is

main = do
	s1 <- B.getLine

	let	s = B.init s1

	let	i = Item (head is) NilItem (B.head s) 0
		is = build 1 i s
		ps = map (\i -> k $ prefix i) is

		n = B.length s

		p = ps !! (n-1)

	if p == 0
	then putStrLn "Just a legend"
	else
		let ps' = filter (== p) (init ps) in
			if ps' /= []
			then B.putStrLn $ B.take (head ps') s
			else
				let p' = ps !! (p - 1) in
				if p' == 0
				then putStrLn "Just a legend"
				else B.putStrLn $ B.take p' s

{-# LANGUAGE BangPatterns, MagicHash #-}
{-# OPTIONS_GHC -O2 -optc-O2 -funbox-strict-fields #-}
import Data.Word

import qualified Data.ByteString as B

data Item = Item { next :: Item, prefix :: Item, ch :: Word8, k :: Int } | NilItem deriving (Eq)

find i c =
	if i' == NilItem || ch i == c then i else find i' c
	where i' = prefix i

build ind !i s =
	Item (head is) i'' (B.head $ B.tail s) ind : is
	where
		i' = find i (B.head s)
		i'' = if ind /= 1 && ch i' == B.head s then next i' else i'
		is = build (ind + 1) i'' (B.tail s)

main = do
	s1 <- B.getLine

	let	s = B.init s1

	let	i = Item (head is) NilItem (B.head s) 0
		is = build 1 i s
		ps = map (\i -> k $ prefix i) is

		n = B.length s

		p = ps !! (n-1)

	if p == 0
	then putStrLn "Just a legend"
	else
		let ps' = filter (== p) (init ps) in
			if ps' /= []
			then B.putStrLn $ B.take (head ps') s
			else
				let p' = ps !! (p - 1) in
				if p' == 0
				then putStrLn "Just a legend"
				else B.putStrLn $ B.take p' s

import Control.Applicative ((<$>))
import Data.List (mapAccumL)
import Data.Array (Array, listArray, elems, (!))
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as C8

zfunc :: Eq a => [a] -> [Int]
zfunc a = elems out
    where
    n = length a :: Int
    mkArray :: [a] -> Array Int a
    mkArray = listArray (0, n - 1)

    arr = mkArray a
    out = mkArray . (n:) . snd $ mapAccumL loop (0, 0) [1..] :: Array Int Int

    loop :: (Int, Int) -> Int -> ((Int, Int), Int)
    loop (l, r) i
        | r < i + 1 = ((i, r'), r' - i)
        | i + out ! (i - l) < r = ((l, r), out ! (i - l))
        | otherwise = ((i, r''), r'' - i)
        where
        next = head . dropWhile (\j -> j < n && arr ! j == arr ! (j - i))
        [r', r''] = map next [[i..], [r..]] :: [Int]

solve :: String -> String
solve [_] = "Just a legend"
solve line = if len /= 0 then take len line else "Just a legend"
    where
    n = length line :: Int
    a = tail . zip [0..] . zfunc $ line :: [(Int, Int)]

    sub = maximum $ map f a :: Int -- longest *strict* substring
        where f (i, k) = if i + k == n then k - 1 else k

    len = maximum $ map f a :: Int
        where f (i, k) = if i + k /= n || sub < k then 0 else k

main = C8.pack . solve . C8.unpack <$> B.getLine >>= C8.putStrLn


Polycarp has $$$3$$$ positive integers $$$a$$$, $$$b$$$ and $$$c$$$. He can perform the following operation exactly once.  Choose a positive integer $$$m$$$ and multiply exactly one of the integers $$$a$$$, $$$b$$$ or $$$c$$$ by $$$m$$$. Can Polycarp make it so that after performing the operation, the sequence of three numbers $$$a$$$, $$$b$$$, $$$c$$$ (in this order) forms an arithmetic progression? Note that you cannot change the order of $$$a$$$, $$$b$$$ and $$$c$$$.Formally, a sequence $$$x_1, x_2, \dots, x_n$$$ is called an arithmetic progression (AP) if there exists a number $$$d$$$ (called "common difference") such that $$$x_{i+1}=x_i+d$$$ for all $$$i$$$ from $$$1$$$ to $$$n-1$$$. In this problem, $$$n=3$$$.For example, the following sequences are AP: $$$[5, 10, 15]$$$, $$$[3, 2, 1]$$$, $$$[1, 1, 1]$$$, and $$$[13, 10, 7]$$$. The following sequences are not AP: $$$[1, 2, 4]$$$, $$$[0, 1, 0]$$$ and $$$[1, 3, 2]$$$.You need to answer $$$t$$$ independent test cases.

The first line contains the number $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Each of the following $$$t$$$ lines contains $$$3$$$ integers $$$a$$$, $$$b$$$, $$$c$$$ ($$$1 \le a, b, c \le 10^8$$$).

For each test case print "YES" (without quotes) if Polycarp can choose a positive integer $$$m$$$ and multiply exactly one of the integers $$$a$$$, $$$b$$$ or $$$c$$$ by $$$m$$$ to make $$$[a, b, c]$$$ be an arithmetic progression. Print "NO" (without quotes) otherwise. You can print YES and NO in any (upper or lower) case (for example, the strings yEs, yes, Yes and YES will be recognized as a positive answer).

YES
YES
YES
YES
NO
YES
NO
YES
YES
NO
YES

NoteIn the first and second test cases, you can choose the number $$$m=4$$$ and multiply the second number ($$$b=5$$$) by $$$4$$$.In the first test case the resulting sequence will be $$$[10, 20, 30]$$$. This is an AP with a difference $$$d=10$$$.In the second test case the resulting sequence will be $$$[30, 20, 10]$$$. This is an AP with a difference $$$d=-10$$$.In the third test case, you can choose $$$m=1$$$ and multiply any number by $$$1$$$. The resulting sequence will be $$$[1, 2, 3]$$$. This is an AP with a difference $$$d=1$$$.In the fourth test case, you can choose $$$m=9$$$ and multiply the first number ($$$a=1$$$) by $$$9$$$. The resulting sequence will be $$$[9, 6, 3]$$$. This is an AP with a difference $$$d=-3$$$.In the fifth test case, it is impossible to make an AP.

import Control.Monad

solve :: IO ()
solve = do
    ~[a, b, c] <- map read . words <$> getLine
    let a' = 2 * b - c
        c' = 2 * b - a
        b' = (c + a) `div` 2
        ok = a' > 0 && a' `mod` a == 0
          || c' > 0 && c' `mod` c == 0
          || even (c - a) && b' > 0 && b' `mod` b == 0
    putStrLn $ if ok then "YES" else "NO"

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

import Data.Char ( isDigit )

main :: IO()
main = do
    tStr <- getLine
    let t = read tStr :: Int
    solve t

solve :: Int -> IO()
solve 0 = return ()
solve t = do

    inStr <- getLine
    let list = readIntList inStr

    let ans = if test list then "YES" else "NO"
    putStrLn ans
    solve (t - 1)

test :: [Int] -> Bool
test [a, b, c]
    | last `mod` c == 0  && last > 0 = True
    | first `mod` a == 0 && first > 0 = True
    | even (a + c) && divisible = True
    | otherwise = False
        where
            first = 2*b - c
            last = 2 * b - a
            divisible = (mid `mod` b) == 0
            mid = (a + c) `div` 2

test _ = False

prog :: [Int] -> Bool
prog [a, b, c]
    | 2 * b == a + c = True
    | otherwise = False
prog _ = False

readIntList :: String -> [Int]
readIntList [] = []
readIntList (h : t)
    | isDigit h = read (takeWhile isDigit (h : t)) : readIntList (dropWhile isDigit t)
    | otherwise = readIntList t

import Control.Monad(replicateM)
import qualified Data.ByteString.Lazy.Char8 as B
import qualified Data.ByteString.Builder.Prim as Prim
import Data.ByteString.Builder
import Control.Monad.Trans.State
import Data.Maybe
import System.IO

divides :: Int -> Int -> Bool
divides a b = b `rem` a == 0

canMakeAP :: Int -> Int -> Int -> Bool
canMakeAP a b c =
  (2*b - c > 0 && a `divides` (2*b - c)) ||
  (2*b) `divides` (c + a) ||
  (2*b - a > 0 && c `divides` (2*b - a))

solve :: SB Builder
solve = do
  ~[t] <- getInts 1
  fmap mconcat $ replicateM t $ do
    ~[a, b, c] <- getInts 3
    let ans = canMakeAP a b c
    return $ string7 (if ans then "YES\n" else "NO\n")

-- stdin/out from solution by clyring
type SB = State [B.ByteString]

getNext :: Int -> SB [B.ByteString]
getNext = state . splitAt

parseInt = fst . fromJust . B.readInt

getInts :: Int -> SB [Int]
getInts n = map parseInt <$> getNext n

main :: IO ()
main = do
  hSetBuffering stdout NoBuffering
  inp <- B.getContents
  let  out = evalState solve $ B.words inp
  B.putStr $ toLazyByteString out

import Control.Monad
import Data.List

main :: IO ()
main = do
  t <- readLn
  replicateM_ t $ do
    [a, b, c] <- map read . words <$> getLine
    putStrLn $ if solve a b c then "YES" else "NO"

solve :: Integer -> Integer -> Integer -> Bool
solve a b c =
  or
    [ let am = 2 * b - c in am > 0 && am `mod` a == 0,
      let bm2 = a + c in bm2 > 0 && bm2 `mod` (b * 2) == 0,
      let cm = 2 * b - a in cm > 0 && cm `mod` c == 0
    ]

-- c - b == b - a * m => a * m - 2 * b + c == 0
-- c - b * m = b * m - a => a - m * 2 * b + c == 0
-- c * m - b = b - a => a - 2 * b + c * m == 0

import Control.Monad (replicateM_)

readInt :: IO Int
readInt = readLn

readIntArray :: IO [Int]
readIntArray = (map read . words) <$> getLine

main :: IO ()
main = readInt >>= \t -> replicateM_ t test

test :: IO ()
test = do
    [a, b, c] <- readIntArray
    putStrLn $ calc a b c

calc :: Int -> Int -> Int -> String
calc a b c
  | (2 * b - c >= 1 && mod (2 * b - c) a == 0)
  || (even (c - a) && mod (div (c + a) 2) b == 0)
  || (2 * b - a >= 1 && mod (2 * b - a) c == 0) = "YES"
  | otherwise = "NO"

-- https://codeforces.com/contest/1624/problem/B
import Control.Monad (replicateM_)

answer a b c
    | (2*b-c >= 1 && (2*b-c)`mod`a == 0)
    ||(even (c-a) && ((c+a)`div`2)`mod`b == 0)
    ||(2*b-a >= 1 && (2*b-a)`mod`c == 0) = "YES"
    | otherwise = "NO"

main = getLine >>= flip replicateM_ run . read
run = do
    [a, b, c] <- (read <$>) . words <$> getLine
    putStrLn $ answer a b c

chunksOf :: Int -> [a] -> [[a]]
chunksOf _ [] = []
chunksOf i xs = take i xs : chunksOf i (drop i xs)

toArr :: Read a => String -> [a]
toArr = map read . words

type InType  = (Int, Int, Int)
type OutType = Bool

solve :: InType -> OutType
solve (a, b, c) =
    let d1 = c - b
        d2 = b - a
        d3 = c - a
    in ((b - d1) `mod` a == 0 && b - d1 >= a) ||
       ((b + d2) `mod` c == 0 && b + d2 >= c) ||
       (even d3 && (a + d3 `div` 2) `mod` b == 0)

receive :: [String] -> InType
receive [s] = case toArr s of
                [a, b, c] -> (a, b, c)
                _         -> error "wrong input"
receive _ = error  "wrong input"

main :: IO ()
main = interact $ unlines . map (showB . solve . receive) . chunksOf 1 . tail . lines
  where showB True = "YES"
        showB False = "NO"

import qualified Data.ByteString.Lazy.Char8 as P
import Data.ByteString.Builder
import qualified Data.ByteString.Builder.Prim as Prim
import System.IO
import Control.Monad.Trans.State
import Data.Maybe

--import Data.ByteString.Builder.Extra (flush) -- for interactive problems
import Control.Monad
--import Data.List
--import Data.Array.Unboxed

mainFun :: SP Builder
mainFun = do
  ~[t] <- getInts 1
  fmap mconcat $ replicateM t $ do
    ~[a, b, c] <- getInts 3
    let
      a' = case  (2 * b - c) `quotRem` a  of
        (q, r) -> r == 0 && q > 0
      b' = (a + c) `rem` (2 * b) == 0
      c' = case  (2 * b - a) `quotRem` c  of
        (q, r) -> r == 0 && q > 0
    pure $ string7 $ if  a' || b' || c'
      then  "YES\n"
      else  "NO\n"

type SP = State [P.ByteString]

getNext :: Int -> SP [P.ByteString]
getNext = state . splitAt

getInts :: Int -> SP [Int]
getInts k = map (fst . fromJust . P.readInt) <$> getNext k

putInts :: [Int] -> Builder
putInts vs = let
  sepPrim = (,) ' ' Prim.>$<
    Prim.liftFixedToBounded Prim.char7 Prim.>*< Prim.intDec
  in  case  vs  of
  [] -> char7 '\n'
  x : xs -> intDec x <> Prim.primMapListBounded sepPrim xs <> char7 '\n'

main :: IO ()
main = do
  hSetBuffering stdout NoBuffering
  inp <- P.getContents
  let  outp = evalState mainFun $ P.words inp
  P.putStr $ toLazyByteString outp

import Control.Monad

solve :: IO ()
solve = do
    ~[a, b, c] <- map read . words <$> getLine
    let a' = 2 * b - c
        c' = 2 * b - a
        b' = (c - a) `div` 2
        ok = a' > 0 && a' `mod` a == 0
          || c' > 0 && c' `mod` c == 0
          || even (c - a) && b' > 0 && b' `mod` b == 0
    putStrLn $ if ok then "YES" else "NO"

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

import Control.Monad

solve :: IO ()
solve = do
    ~[a, b, c] <- map read . words <$> getLine
    let a' = 2 * b - c
        c' = 2 * b - a
        b' = (c - a) `div` 2
        ok = a' > 0 && a' `mod` a == 0
          || c' > 0 && c' `mod` c == 0
          || even (c - a) && b' `mod` b == 0
    putStrLn $ if ok then "YES" else "NO"

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

import Data.Char ( isDigit )

main :: IO()
main = do
    tStr <- getLine
    let t = read tStr :: Int
    solve t

solve :: Int -> IO()
solve 0 = return ()
solve t = do

    inStr <- getLine
    let list = readIntList inStr

    let ans = if test list then "YES" else "NO"
    print ans
    solve (t - 1)

test :: [Int] -> Bool
test [a, b, c]
    | last `mod` c == 0  && last > 0 = True
    | first `mod` a == 0 && first > 0 = True
    | even (a + c) && divisible = True
    | otherwise = False
        where
            first = 2*b - c
            last = 2 * b - a
            divisible = (mid `mod` b) == 0
            mid = (a + c) `div` 2

test _ = False

prog :: [Int] -> Bool
prog [a, b, c]
    | 2 * b == a + c = True
    | otherwise = False
prog _ = False

readIntList :: String -> [Int]
readIntList [] = []
readIntList (h : t)
    | isDigit h = read (takeWhile isDigit (h : t)) : readIntList (dropWhile isDigit t)
    | otherwise = readIntList t


The main characters have been omitted to be short.You are given a directed unweighted graph without loops with $$$n$$$ vertexes and a path in it (that path is not necessary simple) given by a sequence $$$p_1, p_2, \ldots, p_m$$$ of $$$m$$$ vertexes; for each $$$1 \leq i < m$$$ there is an arc from $$$p_i$$$ to $$$p_{i+1}$$$.Define the sequence $$$v_1, v_2, \ldots, v_k$$$ of $$$k$$$ vertexes as good, if $$$v$$$ is a subsequence of $$$p$$$, $$$v_1 = p_1$$$, $$$v_k = p_m$$$, and $$$p$$$ is one of the shortest paths passing through the vertexes $$$v_1$$$, $$$\ldots$$$, $$$v_k$$$ in that order.A sequence $$$a$$$ is a subsequence of a sequence $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly, zero or all) elements. It is obvious that the sequence $$$p$$$ is good but your task is to find the shortest good subsequence.If there are multiple shortest good subsequences, output any of them.

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 100$$$) — the number of vertexes in a graph.  The next $$$n$$$ lines define the graph by an adjacency matrix: the $$$j$$$-th character in the $$$i$$$-st line is equal to $$$1$$$ if there is an arc from vertex $$$i$$$ to the vertex $$$j$$$ else it is equal to $$$0$$$. It is guaranteed that the graph doesn't contain loops. The next line contains a single integer $$$m$$$ ($$$2 \le m \le 10^6$$$) — the number of vertexes in the path.  The next line contains $$$m$$$ integers $$$p_1, p_2, \ldots, p_m$$$ ($$$1 \le p_i \le n$$$) — the sequence of vertexes in the path. It is guaranteed that for any $$$1 \leq i < m$$$ there is an arc from $$$p_i$$$ to $$$p_{i+1}$$$.

In the first line output a single integer $$$k$$$ ($$$2 \leq k \leq m$$$) — the length of the shortest good subsequence. In the second line output $$$k$$$ integers $$$v_1$$$, $$$\ldots$$$, $$$v_k$$$ ($$$1 \leq v_i \leq n$$$) — the vertexes in the subsequence. If there are multiple shortest subsequences, print any. Any two consecutive numbers should be distinct.

NoteBelow you can see the graph from the first example:The given path is passing through vertexes $$$1$$$, $$$2$$$, $$$3$$$, $$$4$$$. The sequence $$$1-2-4$$$ is good because it is the subsequence of the given path, its first and the last elements are equal to the first and the last elements of the given path respectively, and the shortest path passing through vertexes $$$1$$$, $$$2$$$ and $$$4$$$ in that order is $$$1-2-3-4$$$. Note that subsequences $$$1-4$$$ and $$$1-3-4$$$ aren't good because in both cases the shortest path passing through the vertexes of these sequences is $$$1-3-4$$$.In the third example, the graph is full so any sequence of vertexes in which any two consecutive elements are distinct defines a path consisting of the same number of vertexes.In the fourth example, the paths $$$1-2-4$$$ and $$$1-3-4$$$ are the shortest paths passing through the vertexes $$$1$$$ and $$$4$$$.

{- This code was written by
Russell Emerine - linguist,
mathematician, coder,
musician, and metalhead. -}
import Data.Set as Set hiding (map)
import Data.Array.Unboxed as U hiding (map)
import Data.Array.IArray as I hiding (map)

distanceArray :: Array Int [Int] -> Array Int (UArray Int Int)
distanceArray g = I.listArray (1, n) [distances' a' | a' <- [1..n]] where
  n = snd $ bounds g
  distances' :: Int -> UArray Int Int
  distances' a = distances 0 (U.listArray (1, n) [-1 | _ <- [1..n]]) (Set.singleton a)
  distances :: Int -> UArray Int Int -> Set Int -> UArray Int Int
  distances _ result now | Set.null now = result
  distances d pre now = distances (d + 1) result next where
    result = pre // [(a, d) | a <- toList now, pre ! a == -1]
    next = Set.fromList [b | a <- Set.toList now, b <- g ! a, pre ! b == -1]

compress f (p:q:r:ps) = if f ! p ! q + f ! q ! r == f ! p ! r
  then compress f (p:r:ps)
  else p : compress f (q:r:ps)
compress _ ps = ps

makeGraph :: [[Char]] -> Array Int [Int]
makeGraph edges = listArray (1, n) [[j | (j, c) <- zip [1..n] es, c == '1'] | es <- edges] where
  n = length edges

main = do
  line1 <- getLine
  let n = read line1 :: Int
  contents <- getContents
  let
    (grid, query) = Prelude.splitAt n $ lines contents
    g = makeGraph grid
    ps = map read $ words $ head $ tail query
    a = distanceArray g
    result = compress a ps
  print $ length result
  putStrLn $ unwords $ map show result

import Data.Char
import Data.Array.Unboxed
import Data.Array.ST.Safe
import Control.Monad
import Control.Monad.ST
import Data.Maybe
import Data.List

main = do
  n <- readLn
  adj <- listArray ((1,1),(n,n)) . map digitToInt . concat <$> replicateM n getLine :: IO (UArray (Int,Int) Int)
  k <- readLn :: IO Int
  ps <- map read . words <$> getLine :: IO [Int]
  let fw = runSTUArray $ do
        d <- thaw adj
        forM_ (indices adj) $ \p ->
          writeArray d p . (\e -> if e == 0 then 100^3 else 1) =<< readArray d p
        forM_ [1..n] $ \i ->
          forM_ [1..n] $ \j ->
            forM_ [1..n] $ \k -> do
              d0 <- readArray d (i,j)
              d1 <- liftM2 (+) (readArray d (i,k)) (readArray d (k,j))
              when (d1 < d0) $ writeArray d (i,j) d1
        return d
      s = solve fw (maximum (elems fw)) ps
  print (length s)
  putStrLn $ unwords $ map show s

solve fw up (first : ps) = first : go first ps where
  go _ [] = []
  go prev ps = (\(n:ns) -> n : go n ns) $ last $ catMaybes $ zipWith (\d ns@(n:_) -> guard (n /= prev) *> guard (fw!(prev,n) >= d) *> return ns) [1..] $ takeWhile (not . null) $ take up $ tails ps

module Main where

import Control.Monad
import Control.Monad.ST
import Data.Array
import Data.Array.ST.Safe

char2Bool :: Char -> Bool
char2Bool '0' = False
char2Bool '1' = True

enumerate :: [a] -> [(Int, a)]
enumerate = zip [1 ..]

compressAdjMatrix :: [[Bool]] -> Array (Int, Int) Bool
compressAdjMatrix adjMatrix = array ((1, 1), (size, size)) indexedMatrix
    where size = length adjMatrix
          indexedMatrix = do
              (vert,  row) <- enumerate adjMatrix
              (neigh, adj) <- enumerate row
              return ((vert, neigh), adj)

runFloydWarshall :: Array (Int, Int) Bool -> Array (Int, Int) Int
runFloydWarshall adjMatrix = runST $ do
    -- prepare distances
    let (_, (size, _)) = bounds adjMatrix
    let range = [1 .. size]
    distances <- newArray ((1, 1), (size, size)) (size + 1) :: ST s (STUArray s (Int, Int) Int)
    forM_ [(i, j) | i <- range, j <- range] $ \(i, j) -> do
        when (adjMatrix ! (i, j)) $ writeArray distances (i, j) 1
        when (i == j)             $ writeArray distances (i, j) 0

    -- run main algo
    forM_ [(i, u, v) | i <- range, u <- range, v <- range] $ \(i, u, v) -> do
        duv <- readArray distances (u, v)
        dui <- readArray distances (u, i)
        div <- readArray distances (i, v)
        writeArray distances (u, v) $ min duv (dui + div)

    -- return the array
    freeze distances

compressPath :: [Int] -> Array (Int, Int) Int -> [Int]
compressPath path distances = reverse $ go path (tail path) [head path] (head path, 1)
    where go :: [Int] -> [Int] -> [Int] -> (Int,  Int) -> [Int]
          go    (u:_)    []       res      (_, _)       = u : res
          go    (u:us)   (v:vs)   res      (last, c)
            | distances ! (last, v) < c = go us vs (u : res) (u, 2)
            | otherwise                 = go us vs res       (last, succ c)

main :: IO ()
main = do
    size <- read <$> getLine
    matrix <- sequence $ replicate size $ map char2Bool <$> getLine
    pathLength <- (read :: String -> Int) <$> getLine
    path <- map read . words <$> getLine
    let distances = runFloydWarshall $ compressAdjMatrix matrix
        compressedPath = compressPath path distances
    print $ length compressedPath
    putStrLn $ unwords $ map show compressedPath

{- This code was written by
Russell Emerine - linguist,
mathematician, coder,
musician, and metalhead. -}
import Data.Set as Set hiding (map)
import Data.Array.Unboxed as U hiding (map)
import Data.Array.IArray as I hiding (map)

distance :: Array Int [Int] -> Int -> Int -> Int
distance g a b = (I.listArray (1, n) [distances' a' | a' <- [1..n]] :: Array Int (UArray Int Int)) ! a ! b where
  n = snd $ bounds g
  distances' :: Int -> UArray Int Int
  distances' a = distances 0 (U.listArray (1, n) [-1 | _ <- [1..n]]) (Set.singleton a)
  distances :: Int -> UArray Int Int -> Set Int -> UArray Int Int
  distances _ result now | Set.null now = result
  distances d pre now = distances (d + 1) result next where
    result = pre // [(a, d) | a <- toList now]
    next = Set.fromList [b | a <- Set.toList now, b <- g ! a, pre ! b == -1]

compress g (p:q:r:ps) = if distance g p q + distance g q r == distance g p r
  then compress g (p:r:ps)
  else p : compress g (q:r:ps)
compress _ ps = ps

makeGraph :: [[Char]] -> Array Int [Int]
makeGraph edges = listArray (1, n) [[j | (j, c) <- zip [1..n] es, c == '1'] | es <- edges] where
  n = length edges

main = do
  line1 <- getLine
  let n = read line1 :: Int
  contents <- getContents
  let
    (grid, query) = Prelude.splitAt n $ lines contents
    g = makeGraph grid
    ps = map read $ words $ head $ tail query
    result = compress g ps
  print $ length result
  putStrLn $ unwords $ map show result

import Data.Char
import Data.Array.Unboxed
import Data.Array.ST.Safe
import Control.Monad
import Control.Monad.ST
import Data.Maybe
import Data.List

main = do
  n <- readLn
  adj <- listArray ((1,1),(n,n)) . map digitToInt . concat <$> replicateM n getLine :: IO (UArray (Int,Int) Int)
  k <- readLn :: IO Int
  ps <- map read . words <$> getLine :: IO [Int]
  let fw = runSTUArray $ do
        d <- thaw adj
        forM_ (indices adj) $ \p ->
          writeArray d p . (\e -> if e == 0 then 100^3 else 1) =<< readArray d p
        forM_ [1..n] $ \i ->
          forM_ [1..n] $ \j ->
            forM_ [1..n] $ \k -> do
              d0 <- readArray d (i,j)
              d1 <- liftM2 (+) (readArray d (i,k)) (readArray d (k,j))
              when (d1 < d0) $ writeArray d (i,j) d1
        return d
      s = solve fw (maximum (elems fw)) ps
  print (length s)
  putStrLn $ unwords $ map show s

solve fw up (first : ps) = first : go first ps where
  go _ [] = []
  go prev ps = (\(n:ns) -> n : go n ns) $ last $ catMaybes $ zipWith (\d ns@(n:_) -> guard (fw!(prev,n) >= d) *> return ns) [1..] $ takeWhile (not . null) $ take up $ tails ps

import Data.Char
import Data.Array.Unboxed
import Data.Array.ST.Safe
import Control.Monad
import Control.Monad.ST
import Data.Maybe
import Data.List

main = do
  n <- readLn
  adj <- listArray ((1,1),(n,n)) . map digitToInt . concat <$> replicateM n getLine :: IO (UArray (Int,Int) Int)
  k <- readLn :: IO Int
  ps <- map read . words <$> getLine :: IO [Int]
  let fw = runSTUArray $ do
        d <- thaw adj
        forM_ (indices adj) $ \p ->
          writeArray d p . (\e -> if e == 0 then 100^3 else 1) =<< readArray d p
        forM_ [1..n] $ \i ->
          forM_ [1..n] $ \j ->
            forM_ [1..n] $ \k -> do
              d0 <- readArray d (i,j)
              d1 <- liftM2 (+) (readArray d (i,k)) (readArray d (k,j))
              when (d1 < d0) $ writeArray d (i,j) d1
        return d
  putStrLn $ unwords $ map show $ solve fw (maximum (elems fw)) ps

solve fw up (first : ps) = first : go first ps where
  go _ [] = []
  go prev ps = (\(n:ns) -> n : go n ns) $ last $ catMaybes $ zipWith (\d ns@(n:_) -> guard (fw!(prev,n) >= d) *> return ns) [1..] $ takeWhile (not . null) $ take up $ tails ps


Dima took up the biology of bacteria, as a result of his experiments, he invented k types of bacteria. Overall, there are n bacteria at his laboratory right now, and the number of bacteria of type i equals ci. For convenience, we will assume that all the bacteria are numbered from 1 to n. The bacteria of type ci are numbered from  to .With the help of special equipment Dima can move energy from some bacteria into some other one. Of course, the use of such equipment is not free. Dima knows m ways to move energy from some bacteria to another one. The way with number i can be described with integers ui, vi and xi mean that this way allows moving energy from bacteria with number ui to bacteria with number vi or vice versa for xi dollars.Dima's Chef (Inna) calls the type-distribution correct if there is a way (may be non-direct) to move energy from any bacteria of the particular type to any other bacteria of the same type (between any two bacteria of the same type) for zero cost.As for correct type-distribution the cost of moving the energy depends only on the types of bacteria help Inna to determine is the type-distribution correct? If it is, print the matrix d with size k × k. Cell d[i][j] of this matrix must be equal to the minimal possible cost of energy-moving from bacteria with type i to bacteria with type j.

The first line contains three integers n, m, k (1 ≤ n ≤ 105; 0 ≤ m ≤ 105; 1 ≤ k ≤ 500). The next line contains k integers c1, c2, ..., ck (1 ≤ ci ≤ n). Each of the next m lines contains three integers ui, vi, xi (1 ≤ ui, vi ≤ 105; 0 ≤ xi ≤ 104). It is guaranteed that .

If Dima's type-distribution is correct, print string «Yes», and then k lines: in the i-th line print integers d[i][1], d[i][2], ..., d[i][k] (d[i][i] = 0). If there is no way to move energy from bacteria i to bacteria j appropriate d[i][j] must equal to -1. If the type-distribution isn't correct print «No».

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

import Data.List
import Data.Int
import Data.Bits
import Data.Maybe
import Data.Array.Unboxed
import Data.Array.ST
import Data.Array.Base
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.ByteString.Char8 as B
import System.IO

readInt = fromJust . fmap fst . B.readInt
readInts = map readInt . B.words <$> B.getLine
readIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine
readLns :: Read a => IO [a]
readLns = map read . words <$> getLine
cmpFst (a,_) (b,_) = compare a b
cmpSnd (_,a) (_,b) = compare a b
cmpLen a b = length a `compare` length b
swap (a,b) = (b,a)
l2p (a:b:_) = (a,b)
p2l (a,b) = [a,b]
itof :: Int -> Double
itof = fromIntegral
defaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e
defaultArray = accumArray $ curry snd
flatten :: [(a,[(b,c)])] -> [((a,b),c)]
flatten = (=<<) $ uncurry $ fmap . first . (,)

{-
 - make graph with 0-costed edges
 - 各タイプの頂点からdfsして連結成分を求める
 - 同じタイプが異なる連結成分に入っていたら-> No
 - そうでないとき、グラフをつぶしてWF
 - O(n+ k ^ 3)
 -}
main = do
    [n,m,k] <- readInts
    cs <- readInts
    es <- map (map readInt . B.words) . B.lines <$> B.getContents
    let b = typeDistCorrect n m k a es
        a :: UArray Int Int
        a = listArray (1,n) $ do
            (i,ci) <- zip [0..] cs
            take ci $ repeat i
        d = allDist k $ S.toList $ S.fromList $ [((a ! u,a ! v),x) | [u,v,x] <- es, a ! u /= a ! v]
    if b then do
        putStrLn "Yes"
        hFlush stdout
        putStr $ unlines [ unwords [show (let x =  d ! (i,j) in if x == inf then -1 else x) | j <- [0..k-1]] | i <- [0..k-1]]
    else putStrLn "No"

typeDistCorrect n m k ty es = runST $ do
    memo <- newArray (1,n) (-1) :: ST s (STUArray s Int Int)
    l <- forM [1..n] $ \v ->  do
        if v /= 1 && ty ! (v-1) == ty ! v then do
            t1 <- readArray memo v
            t2 <- readArray memo (v-1)
            return (t1 == t2)
        else
            dfs memo (ty ! v) v >> return True
    return $ and l
    where
    es' = do
        [u,v,x] <- es
        guard $ x == 0
        [(u,v),(v,u)]
    g :: Array Int [Int]
    g = accumArray (flip (:)) [] (1,n) es'
    dfs memo t v = do
        t' <- readArray memo v
        if t' /= -1 then return ()
        else do
            writeArray memo v t
            forM_ (g ! v) $ dfs memo t

inf :: Int
inf = 10^9

forM'_ :: Monad m => a -> (a -> Bool) -> (a -> a) -> (a -> m ()) -> m ()
forM'_ i judge incr step = sub i
    where
        sub i | judge i   = step i >> sub (incr i)
              | otherwise = return ()
allDist :: Int -> [((Int,Int),Int)] -> UArray (Int,Int) Int
allDist n es = runSTUArray $ do
    d <- newArray ((0,0),(n-1,n-1)) inf
    forM_ [0..n-1] $ \i -> writeArray d (i,i) 0
    forM_ es $ \(p,c) -> do
        c' <- readArray d p
        when (c' > c) $ do
            writeArray d p c
            writeArray d (swap p) c
    forM'_ 0 (<n) succ $ \k -> forM'_ 0 (<n) succ $ \i -> forM'_ 0 (<n) succ $ \j -> do
        dij <- unsafeRead d (i*n + j)
        dik <- unsafeRead d (i*n + k)
        dkj <- unsafeRead d (k*n + j)
        when (dij > dik + dkj) $ unsafeWrite d (i*n+j) (dik+dkj)
    return d

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

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

readInt = fromJust . fmap fst . B.readInt
readInts = map readInt . B.words <$> B.getLine
readIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine
readLns :: Read a => IO [a]
readLns = map read . words <$> getLine
cmpFst (a,_) (b,_) = compare a b
cmpSnd (_,a) (_,b) = compare a b
cmpLen a b = length a `compare` length b
swap (a,b) = (b,a)
l2p (a:b:_) = (a,b)
p2l (a,b) = [a,b]
itof :: Int -> Double
itof = fromIntegral
defaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e
defaultArray = accumArray $ curry snd
flatten :: [(a,[(b,c)])] -> [((a,b),c)]
flatten = (=<<) $ uncurry $ fmap . first . (,)

{-
 - make graph with 0-costed edges
 - 各タイプの頂点からdfsして連結成分を求める
 - 同じタイプが異なる連結成分に入っていたら-> No
 - そうでないとき、グラフをつぶしてWF
 - O(n+ k ^ 3)
 -}
main = do
    [n,m,k] <- readInts
    cs <- readInts
    es <- map (map readInt . B.words) . B.lines <$> B.getContents
    let b = typeDistCorrect n m k a es
        a :: UArray Int Int
        a = listArray (1,n) $ do
            (i,ci) <- zip [1..] cs
            take ci $ repeat i
        d = allDist k $ S.toList $ S.fromList $ [((a ! u,a ! v),x) | [u,v,x] <- es, a ! u /= a ! v]
    if b then do
        putStrLn "Yes"
        putStr $ unlines [ unwords [show (d !(i,j)) | j <- [1..k]] | i <- [1..k]]
    else putStrLn "No"

typeDistCorrect n m k ty es = runST $ do
    memo <- newArray (1,n) (-1) :: ST s (STUArray s Int Int)
    l <- forM [1..n] $ \v ->  do
        if v /= 1 && ty ! (v-1) == ty ! v then do
            t1 <- readArray memo v
            t2 <- readArray memo (v-1)
            return (t1 == t2 && t1 /= -1)
        else
            dfs memo (ty ! v) v >> return True
    return $ and l
    where
    es' = do
        [u,v,x] <- es
        guard $ x == 0
        [(u,v),(v,u)]
    g :: Array Int [Int]
    g = accumArray (flip (:)) [] (1,n) es'
    dfs memo t v = do
        t' <- readArray memo v
        if t' /= -1 then return ()
        else do
            writeArray memo v t
            forM_ (g ! v) $ dfs memo t

allDist :: Int -> [((Int,Int),Int)] -> UArray (Int,Int) Int
allDist n es = runSTUArray $ do
    d <- newArray ((1,1),(n,n)) (-1)
    forM_ [1..n] $ \i -> writeArray d (i,i) 0
    forM_ es $ \(p,c) -> do
        c' <- readArray d p
        when (c == -1 || c > c') $ do
            writeArray d p c
            writeArray d (swap p) c
    forM_ ((,,) <$> [1..n] <*> [1..n] <*> [1..n]) $ \(k,i,j) -> do
        dij <- readArray d (i,j)
        dik <- readArray d (i,k)
        dkj <- readArray d (k,j)
        when (dij /= -1 && dik /= -1 && dkj /= -1 && dij > dik + dkj) $ writeArray d (i,j) (dik+dkj)
    return d

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

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

readInt = fromJust . fmap fst . B.readInt
readInts = map readInt . B.words <$> B.getLine
readIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine
readLns :: Read a => IO [a]
readLns = map read . words <$> getLine
cmpFst (a,_) (b,_) = compare a b
cmpSnd (_,a) (_,b) = compare a b
cmpLen a b = length a `compare` length b
swap (a,b) = (b,a)
l2p (a:b:_) = (a,b)
p2l (a,b) = [a,b]
itof :: Int -> Double
itof = fromIntegral
defaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e
defaultArray = accumArray $ curry snd
flatten :: [(a,[(b,c)])] -> [((a,b),c)]
flatten = (=<<) $ uncurry $ fmap . first . (,)

{-
 - make graph with 0-costed edges
 - 各タイプの頂点からdfsして連結成分を求める
 - 同じタイプが異なる連結成分に入っていたら-> No
 - そうでないとき、グラフをつぶしてWF
 - O(n+ k ^ 3)
 -}
main = do
    [n,m,k] <- readInts
    cs <- readInts
    es <- map (map readInt . B.words) . B.lines <$> B.getContents
    let b = typeDistCorrect n m k a es
        a :: UArray Int Int
        a = listArray (1,n) $ do
            (i,ci) <- zip [1..] cs
            take ci $ repeat i
        d = allDist k $ S.toList $ S.fromList $ [((a ! u,a ! v),x) | [u,v,x] <- es, a ! u /= a ! v]
    if b then do
        putStrLn "Yes"
        putStr $ unlines [ unwords [show (d !(i,j)) | j <- [1..k]] | i <- [1..k]]
    else putStrLn "No"

typeDistCorrect n m k ty es = runST $ do
    memo <- newArray (1,n) (-1) :: ST s (STUArray s Int Int)
    l <- forM [1..n] $ \v ->  do
        if v /= 1 && ty ! (v-1) == ty ! v then do
            t1 <- readArray memo v
            t2 <- readArray memo (v-1)
            return (t1 == t2)
        else
            dfs memo (ty ! v) v >> return True
    return $ and l
    where
    es' = do
        [u,v,x] <- es
        guard $ x == 0
        [(u,v),(v,u)]
    g :: Array Int [Int]
    g = accumArray (flip (:)) [] (1,n) es'
    dfs memo t v = do
        t' <- readArray memo v
        if t' /= -1 then return ()
        else do
            writeArray memo v t
            forM_ (g ! v) $ dfs memo t

allDist :: Int -> [((Int,Int),Int)] -> UArray (Int,Int) Int
allDist n es = runSTUArray $ do
    d <- newArray ((1,1),(n,n)) (-1)
    forM_ [1..n] $ \i -> writeArray d (i,i) 0
    forM_ es $ \(p,c) -> do
        c' <- readArray d p
        when (c == -1 || c > c') $ do
            writeArray d p c
            writeArray d (swap p) c
    forM_ ((,,) <$> [1..n] <*> [1..n] <*> [1..n]) $ \(k,i,j) -> do
        dij <- readArray d (i,j)
        dik <- readArray d (i,k)
        dkj <- readArray d (k,j)
        when (dij /= -1 && dik /= -1 && dkj /= -1 && dij > dik + dkj) $ writeArray d (i,j) (dik+dkj)
        when (dij == -1 && dik /= -1 && dkj /= -1) $ writeArray d (i,j) (dik+dkj)

    return d

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

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

readInt = fromJust . fmap fst . B.readInt
readInts = map readInt . B.words <$> B.getLine
readIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine
readLns :: Read a => IO [a]
readLns = map read . words <$> getLine
cmpFst (a,_) (b,_) = compare a b
cmpSnd (_,a) (_,b) = compare a b
cmpLen a b = length a `compare` length b
swap (a,b) = (b,a)
l2p (a:b:_) = (a,b)
p2l (a,b) = [a,b]
itof :: Int -> Double
itof = fromIntegral
defaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e
defaultArray = accumArray $ curry snd
flatten :: [(a,[(b,c)])] -> [((a,b),c)]
flatten = (=<<) $ uncurry $ fmap . first . (,)

{-
 - make graph with 0-costed edges
 - 各タイプの頂点からdfsして連結成分を求める
 - 同じタイプが異なる連結成分に入っていたら-> No
 - そうでないとき、グラフをつぶしてWF
 - O(n+ k ^ 3)
 -}
main = do
    [n,m,k] <- readInts
    cs <- readInts
    es <- map (map readInt . B.words) . B.lines <$> B.getContents
    let b = typeDistCorrect n m k a es || True
        a :: UArray Int Int
        a = listArray (1,n) $ do
            (i,ci) <- zip [1..] cs
            take ci $ repeat i
        d = allDist k $ S.toList $ S.fromList $ [((a ! u,a ! v),x) | [u,v,x] <- es, a ! u /= a ! v]
    if b then do
        putStrLn "Yes"
        putStr $ unlines [ unwords [show (let x =  d !(i,j) in if x == inf then -1 else x) | j <- [1..k]] | i <- [1..k]]
    else putStrLn "No"

typeDistCorrect n m k ty es = runST $ do
    memo <- newArray (1,n) (-1) :: ST s (STUArray s Int Int)
    l <- forM [1..n] $ \v ->  do
        if v /= 1 && ty ! (v-1) == ty ! v then do
            t1 <- readArray memo v
            t2 <- readArray memo (v-1)
            return (t1 == t2)
        else
            dfs memo (ty ! v) v >> return True
    return $ and l
    where
    es' = do
        [u,v,x] <- es
        guard $ x == 0
        [(u,v),(v,u)]
    g :: Array Int [Int]
    g = accumArray (flip (:)) [] (1,n) es'
    dfs memo t v = do
        t' <- readArray memo v
        if t' /= -1 then return ()
        else do
            writeArray memo v t
            forM_ (g ! v) $ dfs memo t

inf :: Int
inf = 10^9

forM'_ :: Monad m => a -> (a -> Bool) -> (a -> a) -> (a -> m ()) -> m ()
forM'_ i judge incr step = sub i
    where
        sub i | judge i   = step i >> sub (incr i)
              | otherwise = return ()
allDist :: Int -> [((Int,Int),Int)] -> UArray (Int,Int) Int
allDist n es = runSTUArray $ do
    d <- newArray ((1,1),(n,n)) inf
    forM_ [1..n] $ \i -> writeArray d (i,i) 0
    forM_ es $ \(p,c) -> do
        c' <- readArray d p
        when (c' > c) $ do
            writeArray d p c
            writeArray d (swap p) c
    forM'_ 1 (<=n) succ $ \k -> forM'_ 1 (<=n) succ $ \i -> forM'_ 1 (<=n) succ $ \j -> do
        dij <- readArray d (i,j)
        dik <- readArray d (i,k)
        dkj <- readArray d (k,j)
        when (dij > dik + dkj) $ writeArray d (i,j) (dik+dkj)
    return d

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

import Data.List
import Data.Int
import Data.Bits
import Data.Maybe
import Data.Array.Unboxed
import Data.Array.ST
import Data.Array.Base
import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.ByteString.Char8 as B
import System.IO

readInt = fromJust . fmap fst . B.readInt
readInts = map readInt . B.words <$> B.getLine
readIntPair = l2p . map readInt . take 2 . B.words <$> B.getLine
readLns :: Read a => IO [a]
readLns = map read . words <$> getLine
cmpFst (a,_) (b,_) = compare a b
cmpSnd (_,a) (_,b) = compare a b
cmpLen a b = length a `compare` length b
swap (a,b) = (b,a)
l2p (a:b:_) = (a,b)
p2l (a,b) = [a,b]
itof :: Int -> Double
itof = fromIntegral
defaultArray :: (IArray a e,Ix i) => e -> (i,i) -> [(i,e)] -> a i e
defaultArray = accumArray $ curry snd
flatten :: [(a,[(b,c)])] -> [((a,b),c)]
flatten = (=<<) $ uncurry $ fmap . first . (,)

{-
 - make graph with 0-costed edges
 - 各タイプの頂点からdfsして連結成分を求める
 - 同じタイプが異なる連結成分に入っていたら-> No
 - そうでないとき、グラフをつぶしてWF
 - O(n+ k ^ 3)
 -}
main = do
    [n,m,k] <- readInts
    cs <- readInts
    es <- map (map readInt . B.words) . B.lines <$> B.getContents
    let b = typeDistCorrect n m k a es
        a :: UArray Int Int
        a = listArray (1,n) $ do
            (i,ci) <- zip [0..] cs
            take ci $ repeat i
        d = allDist k $ S.toList $ S.fromList $ [((a ! u,a ! v),x) | [u,v,x] <- es, a ! u /= a ! v]
    if b then do
        putStrLn "Yes"
        hFlush stdout
        putStr $ unlines [ unwords [show (let x =  d ! (i,j) in if x == inf then -1 else x) | j <- [0..k-1]] | i <- [0..k-1]]
    else putStrLn "No"

typeDistCorrect n m k ty es = runST $ do
    memo <- newArray (1,n) (-1) :: ST s (STUArray s Int Int)
    l <- forM [1..n] $ \v ->  do
        if v /= 1 && ty ! (v-1) == ty ! v then do
            t1 <- readArray memo v
            t2 <- readArray memo (v-1)
            return (t1 == t2)
        else
            dfs memo (ty ! v) v >> return True
    return $ and l
    where
    es' = do
        [u,v,x] <- es
        guard $ x == 0
        [(u,v),(v,u)]
    g :: Array Int [Int]
    g = accumArray (flip (:)) [] (1,n) es'
    dfs memo t v = do
        t' <- readArray memo v
        if t' /= -1 then return ()
        else do
            writeArray memo v t
            forM_ (g ! v) $ dfs memo t

inf :: Int
inf = 10^9

forM'_ :: Monad m => a -> (a -> Bool) -> (a -> a) -> (a -> m ()) -> m ()
forM'_ i judge incr step = sub i
    where
        sub i | judge i   = step i >> sub (incr i)
              | otherwise = return ()
allDist :: Int -> [((Int,Int),Int)] -> UArray (Int,Int) Int
allDist n es = runSTUArray $ do
    d <- newArray ((0,0),(n-1,n-1)) inf
    forM_ [0..n-1] $ \i -> writeArray d (i,i) 0
    forM_ es $ \(p,c) -> do
        c' <- readArray d p
        when (c' > c) $ do
            writeArray d p c
            writeArray d (swap p) c
    forM'_ 1 (<=n) succ $ \k -> forM'_ 1 (<=n) succ $ \i -> forM'_ 1 (<=n) succ $ \j -> do
        dij <- unsafeRead d (i*n + j)
        dik <- unsafeRead d (i*n + k)
        dkj <- unsafeRead d (k*n + j)
        when (dij > dik + dkj) $ unsafeWrite d (i*n+j) (dik+dkj)
    return d