Xenia the vigorous detective faced n (n ≥ 2) foreign spies lined up in a row. We'll consider the spies numbered from 1 to n from left to right. Spy s has an important note. He has to pass the note to spy f. Xenia interrogates the spies in several steps. During one step the spy keeping the important note can pass the note to one of his neighbours in the row. In other words, if this spy's number is x, he can pass the note to another spy, either x - 1 or x + 1 (if x = 1 or x = n, then the spy has only one neighbour). Also during a step the spy can keep a note and not pass it to anyone.But nothing is that easy. During m steps Xenia watches some spies attentively. Specifically, during step ti (steps are numbered from 1) Xenia watches spies numbers li, li + 1, li + 2, ..., ri (1 ≤ li ≤ ri ≤ n). Of course, if during some step a spy is watched, he can't do anything: neither give the note nor take it from some other spy. Otherwise, Xenia reveals the spies' cunning plot. Nevertheless, if the spy at the current step keeps the note, Xenia sees nothing suspicious even if she watches him.You've got s and f. Also, you have the steps during which Xenia watches spies and which spies she is going to watch during each step. Find the best way the spies should act in order to pass the note from spy s to spy f as quickly as possible (in the minimum number of steps).

The first line contains four integers n, m, s and f (1 ≤ n, m ≤ 105; 1 ≤ s, f ≤ n; s ≠ f; n ≥ 2). Each of the following m lines contains three integers ti, li, ri (1 ≤ ti ≤ 109, 1 ≤ li ≤ ri ≤ n). It is guaranteed that t1 < t2 < t3 < ... < tm.

Print k characters in a line: the i-th character in the line must represent the spies' actions on step i. If on step i the spy with the note must pass the note to the spy with a lesser number, the i-th character should equal "L". If on step i the spy with the note must pass it to the spy with a larger number, the i-th character must equal "R". If the spy must keep the note at the i-th step, the i-th character must equal "X". As a result of applying the printed sequence of actions spy s must pass the note to spy f. The number of printed characters k must be as small as possible. Xenia must not catch the spies passing the note. If there are miltiple optimal solutions, you can print any of them. It is guaranteed that the answer exists.

import Control.Monad(liftM, forM, forM_)
import Data.Array
import qualified Data.ByteString.Char8 as B
import Data.Maybe(fromJust)
import Data.List(sort)

readi = fst . fromJust . B.readInt

goC s f
	| s < f = 'R'
	| otherwise = 'L'

next s f
	| s == f = s
	| s < f = s + 1
	| otherwise = s - 1

inn x (l, r) = l <= x && x <= r

go s f t [] = replicate (abs (f - s)) (goC s f)
go s f t ls@([t2, l, r]:ev)
	| s == f = ""
	| (t == t2) = if (inn s (l, r) || inn (next s f) (l, r))
			then 'X':(go s f (t + 1) ev)
			else (goC s f):(go ns f (t + 1) ev)
	| otherwise = (goC s f):(go ns f (t + 1) ls)
		where ns = next s f

main = do
	[n, m, s, f] <- (map readi . B.words) `liftM` B.getLine
	tlr <- sequence $ replicate m $ (map readi . B.words) `liftM` B.getLine
	putStr $ go s f 1 (sort tlr)

{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes #-}

import Control.Monad
import Control.Monad.ST
import Control.Applicative
import Control.Arrow
import Debug.Trace

import Data.List
import Data.Int
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 = B.readInt >>> fmap fst >>> fromMaybe 0
readsInt = map readInt . B.words <$> B.getLine
readLine :: Read a => IO a
readLine = read <$> getLine
readsLine :: Read a => IO [a]
readsLine = 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)
rect a b = rect2 0 0 a b
rect2 i j a b = ((i,j),(a,b))

itof :: Int -> Double
itof = fromIntegral
casti = fromIntegral

maximize f l = snd $ maximumBy cmpFst [(f x,x) | x <- l]
minimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]

infixr 2 <||>
infixr 3 <&&>
p1 <||> p2 = (p1 &&& p2) >>> uncurry (||)
p1 <&&> p2 = (p1 &&& p2) >>> uncurry (&&)

convert [a,b,c] = (a,b,c)
main = do
    [n,m,s,f] <- readsInt
    l <- replicateM m (convert <$> readsInt)
    solve n s f l

solve :: Int -> Int -> Int -> [(Int,Int,Int)] -> IO ()
solve n s f l = go s 1 l
    where
    (c,d) = if s < f then ('R',1) else ('L',-1)
    go p _ _ | p == f = putChar '\n'
    go p t ((t',l,r):ls) | t == t' && ((l <= p && p <= r)||(l <= p+d && p+d <= r)) = putChar 'X' >> go p (t+1) ls
                         | t >= t' = putChar c >> go (p+d) (t+1) ls
    go p t ls = putChar c >> go (p+d) (t+1) ls

{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes #-}

import Control.Monad
import Control.Monad.ST
import Control.Applicative
import Control.Arrow
import Debug.Trace

import Data.List
import Data.Int
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 = B.readInt >>> fmap fst >>> fromMaybe 0
readsInt = map readInt . B.words <$> B.getLine
readLine :: Read a => IO a
readLine = read <$> getLine
readsLine :: Read a => IO [a]
readsLine = 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)
rect a b = rect2 0 0 a b
rect2 i j a b = ((i,j),(a,b))

itof :: Int -> Double
itof = fromIntegral
casti = fromIntegral

maximize f l = snd $ maximumBy cmpFst [(f x,x) | x <- l]
minimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]

infixr 2 <||>
infixr 3 <&&>
p1 <||> p2 = (p1 &&& p2) >>> uncurry (||)
p1 <&&> p2 = (p1 &&& p2) >>> uncurry (&&)

convert [a,b,c] = (a,b,c)
main = do
    [n,m,s,f] <- readsInt
    l <- replicateM m (convert <$> readsInt)
    putStrLn $ solve n s f l

solve :: Int -> Int -> Int -> [(Int,Int,Int)] -> String
solve n s f l = go s 1 l
    where
    (c,d) = if s < f then ('R',1) else ('L',-1)
    go p _ _ | p == f = []
    go p t ((t',l,r):ls) | t == t' && ((l <= p && p <= r)||(l <= p+d && p+d <= r)) = 'X' :go p (t+1) ls
                         | t >= t' = c:go (p+d) (t+1) ls
    go p t ls = c:go (p+d) (t+1) ls

{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes #-}

import Control.Monad
import Control.Monad.ST
import Control.Applicative
import Control.Arrow
import Debug.Trace

import Data.List
import Data.Int
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 = B.readInt >>> fmap fst >>> fromMaybe 0
readsInt = map readInt . B.words <$> B.getLine
readLine :: Read a => IO a
readLine = read <$> getLine
readsLine :: Read a => IO [a]
readsLine = 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)
rect a b = rect2 0 0 a b
rect2 i j a b = ((i,j),(a,b))

itof :: Int -> Double
itof = fromIntegral
casti = fromIntegral

maximize f l = snd $ maximumBy cmpFst [(f x,x) | x <- l]
minimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]

infixr 2 <||>
infixr 3 <&&>
p1 <||> p2 = (p1 &&& p2) >>> uncurry (||)
p1 <&&> p2 = (p1 &&& p2) >>> uncurry (&&)

newtype Writer a = Writer { runWriter :: String -> (a,String) }

instance Functor Writer where
    fmap f (Writer g) = Writer (\s -> let (a,s) = g s in (f a,s))

instance Monad Writer where
    return a = Writer (\s -> (a,s))
    (Writer g) >>= f = Writer (\s -> let (a,s') = g s in runWriter (f a) s')

put ch = Writer (\s -> ((),ch:s))

convert [a,b,c] = (a,b,c)
main = do
    [n,m,s,f] <- readsInt
    l <- replicateM m (convert <$> readsInt)
    putStrLn $ solve n s f l

solve :: Int -> Int -> Int -> [(Int,Int,Int)] -> String
solve n s f l = reverse $ snd $ runWriter (go s 1 l) ""
    where
    (c,d) = if s < f then ('R',1) else ('L',-1)
    go p _ _ | p == f = return ()
    go p t ((t',l,r):ls) | t == t' && ((l <= p && p <= r)||(l <= p+d && p+d <= r)) = put 'X' >> go p (t+1) ls
                         | t >= t' = put c >> go (p+d) (t+1) ls
    go p t ls = put c >> go (p+d) (t+1) ls

{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes #-}

import Control.Monad
import Control.Monad.ST
import Control.Applicative
import Control.Arrow
import Debug.Trace

import Data.List
import Data.Int
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 = B.readInt >>> fmap fst >>> fromMaybe 0
readsInt = map readInt . B.words <$> B.getLine
readLine :: Read a => IO a
readLine = read <$> getLine
readsLine :: Read a => IO [a]
readsLine = 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)
rect a b = rect2 0 0 a b
rect2 i j a b = ((i,j),(a,b))

itof :: Int -> Double
itof = fromIntegral
casti = fromIntegral

maximize f l = snd $ maximumBy cmpFst [(f x,x) | x <- l]
minimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]

infixr 2 <||>
infixr 3 <&&>
p1 <||> p2 = (p1 &&& p2) >>> uncurry (||)
p1 <&&> p2 = (p1 &&& p2) >>> uncurry (&&)

newtype Writer a = Writer { runWriter :: ListLike Char -> (a,ListLike Char) }
newtype ListLike a = ListLike { genList :: [a] -> [a] }

instance Functor Writer where
    fmap f (Writer g) = Writer (\s -> let (a,s) = g s in (f a,s))

instance Monad Writer where
    return a = Writer (\s -> (a,s))
    (Writer g) >>= f = Writer (\s -> let (a,s') = g s in runWriter (f a) s')

emptyList = ListLike id
put ch = Writer (\s -> ((),ListLike (\l -> genList s (ch:l))))

convert [a,b,c] = (a,b,c)
main = do
    [n,m,s,f] <- readsInt
    l <- replicateM m (convert <$> readsInt)
    putStrLn $ solve n s f l

solve :: Int -> Int -> Int -> [(Int,Int,Int)] -> String
solve n s f l = genList (snd $ runWriter (go s 1 l) emptyList) ""
    where
    (c,d) = if s < f then ('R',1) else ('L',-1)
    go p _ _ | p == f = return ()
    go p t ((t',l,r):ls) | t == t' && ((l <= p && p <= r)||(l <= p+d && p+d <= r)) = put 'X' >> go p (t+1) ls
                         | t >= t' = put c >> go (p+d) (t+1) ls
    go p t ls = put c >> go (p+d) (t+1) ls

import Control.Monad (liftM)
import Data.List (intercalate)
import Prelude hiding (print, reads)

reads :: IO [Int]
reads  =  liftM (map read . words) getContents
  where
    read s  =  read' 0 s
    read' a ""  =  a
    read' a (c:s)  =  read' (10 * a + fromEnum c - fromEnum '0') s

solve :: [Int] -> String
solve (n : m : s : f : xs)  =  take' l $ solve' 1 s xs
  where
    take' 0 _  =  []
    take' n (x:xs)
      | c == x  =  x : take' (n - 1) xs
      | otherwise  =  x : take' n xs
    l  =  abs (f - s)
    (k, c)  =  if f > s then (1, 'R') else (-1, 'L')
    solve' t s []  =  repeat c
    solve' t s qs@(ti : li : ri : xs)
      | t < ti  =  replicate (ti - t) c ++ solve' ti (s + k * (ti - t)) qs
      | f > s && (s + 1 < li || ri < s)  =  solve' t s xs
      | f < s && (s < li || ri < s - 1)  =  solve' t s xs
      | otherwise  =  'X' : solve' (t+1) s xs

print :: Show a => Maybe [a] -> IO ()
print  =  putStrLn . maybe  "Impossible" (intercalate " " . map show)

main :: IO ()
main  =  reads >>= putStrLn . solve

{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}
{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections #-}

import Control.Applicative
import qualified Data.ByteString.Char8 as B
import Data.Char
import Data.List
import Data.Ord

readInt :: B.ByteString -> Int
readInt bs = case B.readInt bs of Just (n,_) -> n

main :: IO ()
main = do
  [n,m,s,f] <- map read.words <$> getLine
  tlrs <- map readInt.B.words <$> B.getContents
  putStrLn $ solve n s f tlrs

solve :: Int -> Int -> Int -> [Int] -> String
solve n s f tlrs = go s 1 tlrs
   where
     go !cur !time tlrs@(t:l:r:rest)
       | cur == f = ""
       | time > t = go cur time rest
       | time == t && (p l cur r || p l next r) = 'X' : go cur (time+1) rest
       | dir < 0 && cur /= 1 = 'L' : go next (time+1) tlrs
       | dir < 0 = 'X' : go cur (time+1) tlrs
       | dir > 0 && cur /= n = 'R' : go next (time+1) tlrs
       | otherwise = 'X' : go cur (time+1) tlrs
      where
        p l x r = l<=x && x<=r
        dir = signum (f - cur)
        next = cur + dir
     go !cur !time []
       | cur == f = ""
       | dir < 0 && cur /= 1 = 'L' : go next (time+1) []
       | dir < 0 = 'X' : go cur (time+1) []
       | dir > 0 && cur /= n = 'R' : go next (time+1) []
       | otherwise = 'X' : go cur (time+1) []
      where
        dir = signum (f - cur)
        next = cur + dir

import Control.Monad (replicateM)

main :: IO ()
main = do
    [n, m, s, f] <- getWords
    blocks <- replicateM m $ do
        [t, l, r] <- getWords
        return (t, l, r)
    putStrLn $ solve s f blocks

solve :: Int -> Int -> [(Int, Int, Int)] -> String
solve source destination blocks = map showStep $ solve' source blocks 1 where
    showStep True  = if source < destination then 'R' else 'L'
    showStep False = 'X'

    solve' source blocks time
        | source == destination = []
        | null blocks = replicate (abs (destination - source)) True
        | t < time    = solve' source (tail blocks) time
        | otherwise   = canGo : solve' source' blocks (time + 1)
        where
            (t, l, r) = head blocks

            source' = if canGo then next else source
            canGo = not $ isBlocked source || isBlocked next
            next = if source < destination
                   then source + 1
                   else source - 1

            isBlocked x = t == time && l <= x && x <= r

getWords :: Read a => IO [a]
getWords = getLine >>= return . map read . words

import Control.Monad(liftM, forM, forM_)
import Data.Array
import qualified Data.ByteString.Char8 as B
import Data.Maybe(fromJust)
import Data.List(sort)

readi = fst . fromJust . B.readInt

goC s f
	| s < f = 'R'
	| otherwise = 'L'

next s f
	| s == f = s
	| s < f = s + 1
	| otherwise = s - 1

inn x (l, r) = l <= x && x <= r

go s f t [] = replicate (f - s) (goC s f)
go s f t ls@([t2, l, r]:ev)
	| s == f = ""
	| (t == t2) = if (inn s (l, r) || inn (next s f) (l, r))
			then 'X':(go s f (t + 1) ev)
			else (goC s f):(go ns f (t + 1) ev)
	| otherwise = (goC s f):(go ns f (t + 1) ls)
		where ns = next s f

main = do
	[n, m, s, f] <- (map readi . B.words) `liftM` B.getLine
	tlr <- sequence $ replicate m $ (map readi . B.words) `liftM` B.getLine
	putStr $ go s f 1 (sort tlr)

import Control.Monad(liftM, forM, forM_)
import Data.Array
import qualified Data.ByteString.Char8 as B
import Data.Maybe(fromJust)
import Data.List(sort)

readi = fst . fromJust . B.readInt

goC s f
	| s < f = 'R'
	| otherwise = 'L'

next s f
	| s == f = s
	| s < f = s + 1
	| otherwise = s - 1

inn x (l, r) = l <= x && x <= r

go s f t [] = replicate (t + (f - s)) (goC s f)
go s f t ls@([t2, l, r]:ev)
	| s == f = ""
	| (t == t2) = if (inn s (l, r) || inn (next s f) (l, r))
			then 'X':(go s f (t + 1) ev)
			else (goC s f):(go ns f (t + 1) ev)
	| otherwise = (goC s f):(go ns f (t + 1) ls)
		where ns = next s f

main = do
	[n, m, s, f] <- (map readi . B.words) `liftM` B.getLine
	tlr <- sequence $ replicate m $ (map readi . B.words) `liftM` B.getLine
	putStr $ go s f 1 (sort tlr)

{-# LANGUAGE MultiParamTypeClasses,FlexibleContexts,FlexibleInstances,TypeSynonymInstances,BangPatterns,RankNTypes #-}

import Control.Monad
import Control.Monad.ST
import Control.Applicative
import Control.Arrow
import Debug.Trace

import Data.List
import Data.Int
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 = B.readInt >>> fmap fst >>> fromMaybe 0
readsInt = map readInt . B.words <$> B.getLine
readLine :: Read a => IO a
readLine = read <$> getLine
readsLine :: Read a => IO [a]
readsLine = 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)
rect a b = rect2 0 0 a b
rect2 i j a b = ((i,j),(a,b))

itof :: Int -> Double
itof = fromIntegral
casti = fromIntegral

maximize f l = snd $ maximumBy cmpFst [(f x,x) | x <- l]
minimize f l = snd $ minimumBy cmpFst [(f x,x) | x <- l]

infixr 2 <||>
infixr 3 <&&>
p1 <||> p2 = (p1 &&& p2) >>> uncurry (||)
p1 <&&> p2 = (p1 &&& p2) >>> uncurry (&&)

newtype Writer a = Writer { runWriter :: ListLike Char -> (a,ListLike Char) }
newtype ListLike a = ListLike { genList :: [a] -> [a] }

instance Functor Writer where
    fmap f (Writer g) = Writer (\s -> let (a,s) = g s in (f a,s))

instance Monad Writer where
    return a = Writer (\s -> (a,s))
    (Writer g) >>= f = Writer (\s -> let (a,s') = g s in runWriter (f a) s')

emptyList = ListLike id
put ch = Writer (\s -> ((),ListLike (\l -> ch:l)))

convert [a,b,c] = (a,b,c)
main = do
    [n,m,s,f] <- readsInt
    l <- replicateM m (convert <$> readsInt)
    putStrLn $ solve n s f l

solve :: Int -> Int -> Int -> [(Int,Int,Int)] -> String
solve n s f l = genList (snd $ runWriter (go s 1 l) emptyList) ""
    where
    (c,d) = if s < f then ('R',1) else ('L',-1)
    go p _ _ | p == f = return ()
    go p t ((t',l,r):ls) | t == t' && ((l <= p && p <= r)||(l <= p+d && p+d <= r)) = put 'X' >> go p (t+1) ls
                         | t >= t' = put c >> go (p+d) (t+1) ls
    go p t ls = put c >> go (p+d) (t+1) ls

{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}
{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections #-}

import Control.Applicative
import qualified Data.ByteString.Char8 as B
import Data.Char
import Data.List
import Data.Ord

readInt :: B.ByteString -> Int
readInt bs = case B.readInt bs of Just (n,_) -> n

main :: IO ()
main = do
  [n,m,s,f] <- map read.words <$> getLine
  tlrs <- map readInt.B.words <$> B.getContents
  putStrLn $ solve n s f tlrs

solve :: Int -> Int -> Int -> [Int] -> String
solve n s f tlrs = go s 1 tlrs
   where
     go !cur !time (t:l:r:rest)
       | cur == f = ""
       | time == t && l<=next && next<=r = 'X' : go cur (time+1) rest
       | dir < 0 && cur /= 1 = 'L' : go next (time+1) rest
       | dir < 0 = 'X' : go cur (time+1) rest
       | dir > 0 && cur /= n = 'R' : go next (time+1) rest
       | otherwise = 'X' : go cur (time+1) rest
      where
        dir = signum (f - cur)
        next = cur + dir
     go !cur !time []
       | cur == f = ""
       | dir < 0 && cur /= 1 = 'L' : go next (time+1) []
       | dir < 0 = 'X' : go cur (time+1) []
       | dir > 0 && cur /= n = 'R' : go next (time+1) []
       | otherwise = 'X' : go cur (time+1) []
      where
        dir = signum (f - cur)
        next = cur + dir

{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}
{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections #-}

import Control.Applicative
import qualified Data.ByteString.Char8 as B
import Data.Char
import Data.List
import Data.Ord

readInt :: B.ByteString -> Int
readInt bs = case B.readInt bs of Just (n,_) -> n

main :: IO ()
main = do
  [n,m,s,f] <- map read.words <$> getLine
  tlrs <- map readInt.B.words <$> B.getContents
  putStrLn $ solve n s f tlrs

solve :: Int -> Int -> Int -> [Int] -> String
solve n s f tlrs = go s 1 tlrs
   where
     go !cur !time tlrs@(t:l:r:rest)
       | cur == f = ""
       | time == t && (p l cur r || p l next r) = 'X' : go cur (time+1) rest
       | dir < 0 && cur /= 1 = 'L' : go next (time+1) tlrs
       | dir < 0 = 'X' : go cur (time+1) tlrs
       | dir > 0 && cur /= n = 'R' : go next (time+1) tlrs
       | otherwise = 'X' : go cur (time+1) tlrs
      where
        p l x r = l<=x && x<=r
        dir = signum (f - cur)
        next = cur + dir
     go !cur !time []
       | cur == f = ""
       | dir < 0 && cur /= 1 = 'L' : go next (time+1) []
       | dir < 0 = 'X' : go cur (time+1) []
       | dir > 0 && cur /= n = 'R' : go next (time+1) []
       | otherwise = 'X' : go cur (time+1) []
      where
        dir = signum (f - cur)
        next = cur + dir

{-# OPTIONS_GHC -O2 -funbox-strict-fields #-}
{-# LANGUAGE BangPatterns, ViewPatterns, TupleSections #-}

import Control.Applicative
import qualified Data.ByteString.Char8 as B
import Data.Char
import Data.List
import Data.Ord

readInt :: B.ByteString -> Int
readInt bs = case B.readInt bs of Just (n,_) -> n

main :: IO ()
main = do
  [n,m,s,f] <- map read.words <$> getLine
  tlrs <- map readInt.B.words <$> B.getContents
  putStrLn $ solve n s f tlrs

solve :: Int -> Int -> Int -> [Int] -> String
solve n s f tlrs = go s 1 tlrs
   where
     go !cur !time (t:l:r:rest)
       | cur == f = ""
       | time == t && (p l cur r || p l next r) = 'X' : go cur (time+1) rest
       | dir < 0 && cur /= 1 = 'L' : go next (time+1) rest
       | dir < 0 = 'X' : go cur (time+1) rest
       | dir > 0 && cur /= n = 'R' : go next (time+1) rest
       | otherwise = 'X' : go cur (time+1) rest
      where
        p l x r = l<=x && x<=r
        dir = signum (f - cur)
        next = cur + dir
     go !cur !time []
       | cur == f = ""
       | dir < 0 && cur /= 1 = 'L' : go next (time+1) []
       | dir < 0 = 'X' : go cur (time+1) []
       | dir > 0 && cur /= n = 'R' : go next (time+1) []
       | otherwise = 'X' : go cur (time+1) []
      where
        dir = signum (f - cur)
        next = cur + dir


Hongcow likes solving puzzles.One day, Hongcow finds two identical puzzle pieces, with the instructions "make a rectangle" next to them. The pieces can be described by an n by m grid of characters, where the character 'X' denotes a part of the puzzle and '.' denotes an empty part of the grid. It is guaranteed that the puzzle pieces are one 4-connected piece. See the input format and samples for the exact details on how a jigsaw piece will be specified.The puzzle pieces are very heavy, so Hongcow cannot rotate or flip the puzzle pieces. However, he is allowed to move them in any directions. The puzzle pieces also cannot overlap.You are given as input the description of one of the pieces. Determine if it is possible to make a rectangle from two identical copies of the given input. The rectangle should be solid, i.e. there should be no empty holes inside it or on its border. Keep in mind that Hongcow is not allowed to flip or rotate pieces and they cannot overlap, i.e. no two 'X' from different pieces can share the same position.

The first line of input will contain two integers n and m (1 ≤ n, m ≤ 500), the dimensions of the puzzle piece. The next n lines will describe the jigsaw piece. Each line will have length m and will consist of characters '.' and 'X' only. 'X' corresponds to a part of the puzzle piece, '.' is an empty space. It is guaranteed there is at least one 'X' character in the input and that the 'X' characters form a 4-connected region.

Output "YES" if it is possible for Hongcow to make a rectangle. Output "NO" otherwise.

NoteFor the first sample, one example of a rectangle we can form is as follows 111222111222For the second sample, it is impossible to put two of those pieces without rotating or flipping to form a rectangle.In the third sample, we can shift the first tile by one to the right, and then compose the following rectangle: .......XX................

{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE BangPatterns #-}

import Control.Applicative
import Control.Monad
import Control.Arrow
import Data.List
import Data.Maybe
import Data.Char
import qualified Data.ByteString.Char8 as B
import Text.Printf

readInt = ( readLn :: IO Int )
readInts = map ( read :: String -> Int ) . words <$> getLine

getList = map ( fst . fromJust . B.readInt ) . B.words <$> B.getLine

which a b f = if f then a else b
mp [ a, b ] = ( a, b )

main = getLine >> getContents >>= putStrLn . which "YES" "NO" . all ( all ( == 'X' ) ) . clip . transpose . clip . lines

clip = filter ( not . all ( == '.' ) )

import Data.List

-- solvable iff input shape is a rectangle
solve :: [String] -> Bool
solve strs =
  let blank = all (=='.')
      dropBlanks = filter (not . blank)
      strs' = dropBlanks $ transpose $ dropBlanks strs
      allXSegments = all (all (=='X'))
  in allXSegments strs'

main :: IO ()
main = do
  _ <- getLine
  rst <- getContents
  let soln = solve $ lines rst
  if soln then
    putStrLn "YES"
    else putStrLn "NO"

import Control.Monad( replicateM)
import Data.List( nub)
main = do
    [n_, m_] <- return.map read.words =<< getLine
    ls <- replicateM n_ getLine
    let cleansed = filter (any ('X'==)) ls
    putStr $ if 1 == (length $ nub cleansed) then "YES" else "NO"


Everyone knows that hobbits love to organize all sorts of parties and celebrations. There are n hobbits living in the Shire. They decided to organize the Greatest Party (GP) that would last for several days. Next day the hobbits wrote a guest list, some non-empty set containing all the inhabitants of the Shire. To ensure that everybody enjoy themselves and nobody gets bored, for any two days (say, days A and B) of the GP there existed at least one hobbit, invited to come on day A and on day B. However, to ensure that nobody has a row, for any three different days A, B, C there shouldn't be a hobbit invited on days A, B and C. The Shire inhabitants are keen on keeping the GP going for as long as possible. Your task is given number n, to indicate the GP's maximum duration and the guest lists for each day.

The first line contains an integer n (3 ≤ n ≤ 10000), representing the number of hobbits.

In the first output line print a number k — the maximum duration of GP in days. Then on k lines print the guest lists, (the guests should be separated by spaces). Print each guest list on the single line. Each list can contain an arbitrary positive number of hobbits. The hobbits are numbered with integers from 1 to n.

import Data.Function
import List

main = readLn >>= putStrLn . solve

solve n = show k ++ "\n" ++ unlines [unwords $ map (show . snd) day | day <- lst3 ]
  where
    k = last $ takeWhile (\x -> x * (x - 1) `div` 2 <= n) [1..]
    lst = [(i, j) | i <- [1..k], j <- [1..i-1]]

    lst2 = concat [[(pi, i), (pj, i)] | (i, (pi, pj)) <- zip [1..] lst]

    lst3 = groupBy ((==) `on` fst) $ sort lst2

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

comb :: Integral b => b -> [a] -> [[a]]
comb 0 _        = [[]]
comb _ []       = []
comb n (x : xs) = map (x :) (comb (n - 1) xs) ++ comb n xs

icomb :: Integer -> Integer -> Integer
icomb n m = product [n, n - 1 .. n - m + 1] `quot` product [1 .. m]

participants :: Int -> [[Int]]
participants n = [[x, x] | x <- [1 .. n]]

solve :: Int -> [(Int, [Int])]
solve n = map ((,) <$> fst . head <*> map snd) . groupBy ((==) `on` fst) . sort $
  f (comb 2 [1 .. days]) (participants n)
 where
  days = (+ 2) $ length $ (takeWhile (<= n')) $ map (`icomb` 2) [3 ..]
   where n' = toInteger n
  f []          bss           = []
  f ~(as : ass) ~(bs : bss)   = zip as bs ++ f ass bss

main :: IO ()
main = do
  xs <- solve <$> readLn
  print $ length xs
  forM_ xs $ \(_, hobbits) ->
    putStrLn $ drop 1 $ hobbits >>= printf " %s" . show

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

comb :: Integral b => b -> [a] -> [[a]]
comb 0 _        = [[]]
comb _ []       = []
comb n (x : xs) = map (x :) (comb (n - 1) xs) ++ comb n xs

participants :: Int -> [[Int]]
participants n = [[x, x] | x <- [1 .. n]]

solve :: Int -> [(Int, [Int])]
solve n = map ((,) <$> fst . head <*> map snd) . groupBy ((==) `on` fst) . sort $
  loop 3 (participants n)
 where
  loop days xs = case f [] (comb 2 [1 .. days]) xs of
    Nothing         -> []
    Just (acc, xs') -> acc ++ loop (days + 1) xs'
   where
    f acc []          bss          = Just (acc, bss)
    f _   _           []           = Nothing
    f acc (as : ass)  (bs : bss) = f (zip as bs ++ acc) ass bss

main :: IO ()
main = do
  xs <- solve <$> readLn
  print $ length xs
  forM_ xs $ \(_, hobbits) ->
    putStrLn $ drop 1 $ hobbits >>= printf " %s" . show


Once at a team training Vasya, Petya and Sasha got a problem on implementing linear search in an array.According to the boys, linear search works as follows. The array elements in a pre-selected order are in turn compared with the number that you need to find. Once you find the array element that is equal to the required one, the search ends. The efficiency of the algorithm is the number of performed comparisons. The fewer comparisons the linear search has made, the more effective it is.Vasya believes that a linear search would work better if it sequentially iterates through the elements, starting with the 1-st one (in this problem we consider the elements of the array indexed from 1 to n) and ending with the n-th one. And Petya says that Vasya is wrong: the search will need less comparisons if it sequentially iterates the elements starting from the n-th and ending with the 1-st one. Sasha argues that the two approaches are equivalent.To finally begin the task, the teammates decided to settle the debate and compare the two approaches on an example. For this, they took an array that is a permutation of integers from 1 to n, and generated m queries of the form: find element with value bi in the array. They want to calculate for both approaches how many comparisons in total the linear search will need to respond to all queries. If the first search needs fewer comparisons, then the winner of the dispute is Vasya. If the second one does, then the winner is Petya. If both approaches make the same number of comparisons, then Sasha's got the upper hand.But the problem is, linear search is too slow. That's why the boys aren't going to find out who is right before the end of the training, unless you come in here. Help them to determine who will win the dispute.

The first line contains integer n (1 ≤ n ≤ 105) — the number of elements in the array. The second line contains n distinct space-separated integers a1, a2, ..., an (1 ≤ ai ≤ n) — the elements of array.  The third line contains integer m (1 ≤ m ≤ 105) — the number of queries. The last line contains m space-separated integers b1, b2, ..., bm (1 ≤ bi ≤ n) — the search queries. Note that the queries can repeat.

Print two integers, showing how many comparisons Vasya's approach needs and how many comparisons Petya's approach needs. Separate the numbers by spaces. Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specifier.

NoteIn the first sample Vasya's approach will make one comparison (it starts with the 1-st element and immediately finds the required number), and Petya's approach makes two comparisons (first he compares with the 2-nd array element, doesn't find the search item and compares with the 1-st element).In the second sample, on the contrary, Vasya's approach will need two comparisons (first with 1-st element, and then with the 2-nd), and Petya's approach will find the required value in one comparison (the first comparison with the 2-nd element).

import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.List as L
import qualified Data.Array as A
import Data.Int

solve :: Int64 -> Int64 -> [Int64] -> [Int64] -> [Int64]
solve n m al bl = [query first bl,query last bl]
    where
        first = A.array (1,n) $ zip al [1..]
        last  = A.array (1,n) $ zip (reverse al) [1..]
        query ary  = L.foldl' (\e k -> e +  (ary A.! k)) 0

main :: IO ()
main = do n  <- (getLine >>= return . read)
          al <- (getLine >>= return . map read . words)
          m  <- (getLine >>= return . read)
          bl <- (getLine >>= return . map read . words)
          putStrLn . unwords . map show $ solve n m al bl

import Array

solve :: Integer -> Array Int Int -> [Int] -> (Integer, Integer)
solve n array qs  =  foldl acc (0, 0) qs
  where
    acc (s1, s2) q  =  s1' `seq` s2' `seq` (s1', s2')
      where
        s1'  =  s1 + a
        s2'  =  s2 + n + 1 - a
        a    =  fromIntegral (array ! q)

main :: IO ()
main  =  do
    n   <-  readLn
    as  <-  fmap (map read . words) getLine
    getLine
    qs  <-  fmap (map read . words) getLine
    let (a, b)  =  solve n (array (1, fromIntegral n) (zip as [1..])) qs
    putStrLn $ concat [show a, " ", show b]

import qualified Data.Map as M
import qualified Data.Set as S
import qualified Data.List as L
import qualified Data.Maybe as Maybe

solve :: Int -> Int -> [Int] -> [Int] -> [Int]
solve n m al bl = [query firstMap bl,query lastMap bl]
    where
        firstMap = M.fromListWith (\a b -> a) $ zip al [1..]
        lastMap  = M.fromListWith (\a b -> a) $ zip (reverse al) [1..]
        query m  = L.foldl' (\e k -> e +  (Maybe.fromJust $ M.lookup k m)) 0

main :: IO ()
main = do n  <- (getLine >>= return . read)
          al <- (getLine >>= return . map read . words)
          m  <- (getLine >>= return . read)
          bl <- (getLine >>= return . map read . words)
          putStrLn . unwords . map show $ solve n m al bl


John Smith knows that his son, Thomas Smith, is among the best students in his class and even in his school. After the students of the school took the exams in English, German, Math, and History, a table of results was formed.There are $$$n$$$ students, each of them has a unique id (from $$$1$$$ to $$$n$$$). Thomas's id is $$$1$$$. Every student has four scores correspond to his or her English, German, Math, and History scores. The students are given in order of increasing of their ids.In the table, the students will be sorted by decreasing the sum of their scores. So, a student with the largest sum will get the first place. If two or more students have the same sum, these students will be sorted by increasing their ids. Please help John find out the rank of his son.

The first line contains a single integer $$$n$$$ ($$$1 \le n \le 1000$$$) — the number of students. Each of the next $$$n$$$ lines contains four integers $$$a_i$$$, $$$b_i$$$, $$$c_i$$$, and $$$d_i$$$ ($$$0\leq a_i, b_i, c_i, d_i\leq 100$$$) — the grades of the $$$i$$$-th student on English, German, Math, and History. The id of the $$$i$$$-th student is equal to $$$i$$$.

Print the rank of Thomas Smith. Thomas's id is $$$1$$$.

NoteIn the first sample, the students got total scores: $$$398$$$, $$$400$$$, $$$398$$$, $$$379$$$, and $$$357$$$. Among the $$$5$$$ students, Thomas and the third student have the second highest score, but Thomas has a smaller id, so his rank is $$$2$$$.In the second sample, the students got total scores: $$$369$$$, $$$240$$$, $$$310$$$, $$$300$$$, $$$300$$$, and $$$0$$$. Among the $$$6$$$ students, Thomas got the highest score, so his rank is $$$1$$$.

import Data.List
f ::Int->[String]->[(Int,Int)]
f _ []=[]
f p (x:xs)=(sum ( map read (words x)::[Int]),-p):f (p+1) xs

g ::Int->[(Int,Int)]->Int
g ans ((_,(-1)):xs)=ans
g ans (_:xs)=g (ans+1) xs

main = do
       e1<-getLine
       es<-getContents
       let n=read e1::Int
           xs=lines es
           ys=reverse $ sort $ f 1 xs
       print $ g 1 ys

{-# LANGUAGE ScopedTypeVariables #-}

import Prelude
import Data.Maybe
import Data.List
import Text.Printf
import Control.Monad
import Data.Ratio
import Data.Int
import Data.Functor
import Control.Monad.ST.Safe
import Data.STRef
import Data.Monoid
import Data.Ord
import qualified Data.Array.IArray as IA
import qualified Data.Array.MArray.Safe as MA
import qualified Data.Array.ST.Safe as A
import qualified Data.Array.Unboxed as UA
import qualified Data.ByteString.Char8 as B8

main :: IO ()
main = do
    (n :: Int) <- read <$> getLine
    (arr :: [[Int]]) <- replicateM n ((map read . words) <$> getLine)
    let sortedArr = sortBy (\(x1, y1) (x2, y2) -> comparing sum x2 x1 `mappend` compare y1 y2) $ zip arr [1..]
    printf "%d" $ (+ 1) $ fromJust $ findIndex (\(_, y) -> y == 1) sortedArr

import Data.List
import Data.Ord
main = interact $ show . succ . head . findIndices ((== 1) . snd) . sort . flip zip [1..] . map (Down . sum . map read . words) . tail . lines

import Control.Applicative
import Control.Monad
import Data.List
import Data.Maybe
import Data.Array

main = do
	n <- read <$> getLine ::IO Int
	s <- map sum <$> map (map read ) <$> map words  <$> replicateM n getLine:: IO [Int]
	let j = head s
	print $ 1+ length ( takeWhile (>j)(reverse  (sort s)))

module Main where
import Data.List
import Data.Monoid
import Data.Maybe

default (Int)

main = interact exec
exec = show . succ . fromJust . findIndex (\(i, _) -> i == 1) . sortBy (\(i1, s1) (i2, s2) -> compare s2 s1 `mappend` compare i1 i2) . zip [1..] . chunks . tail . map read . words
  where
    chunks (a:b:c:d:xs) = (a + b + c + d):chunks xs
    chunks [] = []

--ghc 7.10

import Data.List(sortBy, findIndex)
import Data.Ord(comparing)
import Data.Maybe(fromJust)

rank :: [[Int]] -> Int
rank = (1+) . fromJust . findIndex (\x -> fst x == 1) . sortBy (flip $ comparing snd) . zip [1..] . map sum

main = do
    nStr <- getLine
    contents <- getContents
    let grades = map (map read . words) . lines $ contents
    print $ rank grades

{-# LANGUAGE ScopedTypeVariables #-}

import Prelude
import Data.Maybe
import Data.List
import Text.Printf
import Control.Monad
import Data.Ratio
import Data.Int
import Data.Functor
import Control.Monad.ST.Safe
import Data.STRef
import Data.Monoid
import qualified Data.Array.IArray as IA
import qualified Data.Array.MArray.Safe as MA
import qualified Data.Array.ST.Safe as A
import qualified Data.Array.Unboxed as UA
import qualified Data.ByteString.Char8 as B8

main :: IO ()
main = do
    (n :: Int) <- read <$> getLine
    (arr :: [[Int]]) <- replicateM n ((map read . words) <$> getLine)
    let sortedArr = sortBy (\(x1, y1) (x2, y2) -> compare x2 x1 `mappend` compare y1 y2) $ zip arr [1..]
    printf "%d" $ fromJust $ findIndex (\(_, y) -> y == 1) sortedArr

import Data.List
import Data.Ord
main = interact $ show . unDown . fst . head . filter ((== 1) . snd) . sort . flip zip [1..] . map (Down . sum . map read . words) . tail . lines
unDown (Down x) = x

import Control.Applicative
import Control.Monad
import Data.List
import Data.Maybe
import Data.Array

main = do
	n <- read <$> getLine ::IO Int
	s <- map sum <$> map (map read ) <$> map words  <$> replicateM n getLine:: IO [Int]
	let j = head s
	print $ 1+ length ( takeWhile (>j) (sort s))

import Control.Applicative
import Control.Monad
import Data.List
import Data.Maybe
import Data.Array

main = do
	n <- read <$> getLine ::IO Int
	s <- map sum <$> map (map read ) <$> map words  <$> replicateM n getLine:: IO [Int]
	let j = head s
	print $ 1+ length ( takeWhile (>j) s)


The only difference between the easy and the hard version is the limit to the number of queries.This is an interactive problem.There is an array $$$a$$$ of $$$n$$$ different numbers. In one query you can ask the position of the second maximum element in a subsegment $$$a[l..r]$$$. Find the position of the maximum element in the array in no more than 20 queries.A subsegment $$$a[l..r]$$$ is all the elements $$$a_l, a_{l + 1}, ..., a_r$$$. After asking this subsegment you will be given the position of the second maximum from this subsegment in the whole array.

The first line contains a single integer $$$n$$$ $$$(2 \leq n \leq 10^5)$$$ — the number of elements in the array.

NoteIn the sample suppose $$$a$$$ is $$$[5, 1, 4, 2, 3]$$$. So after asking the $$$[1..5]$$$ subsegment $$$4$$$ is second to max value, and it's position is $$$3$$$. After asking the $$$[4..5]$$$ subsegment $$$2$$$ is second to max value and it's position in the whole array is $$$4$$$.Note that there are other arrays $$$a$$$ that would produce the same interaction, and the answer for them might be different. Example output is given in purpose of understanding the interaction.

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

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

boolInt :: Bool -> Int
boolInt p = if  p  then  1  else  0

query :: Int -> Int -> SIO Int
query li ri = let
  outBuilder = foldr (<>) (B.char7 '\n')
    $ intersperse (B.char7 ' ') (B.char7 '?' : map B.intDec [li, ri])
  in  do
  lift $ B.hPutBuilder stdout outBuilder >> hFlush stdout
  [response] <- readInts
  pure response

go :: Int -> Int -> Int -> SIO Int
go v li ri = let
  mi = div (li + ri) 2
  in  if  li + boolInt (elem v [li, ri]) == ri
  then  pure $ if  v == li
    then  ri
    else  li
  else  if  v < li
  then  do
    resp <- query v mi
    if  resp == v
      then  go v li mi
      else  go v (mi+1) ri
  else  if  ri < v
  then  do
    resp <- query (mi+1) v
    if  resp == v
      then  go v (mi+1) ri
      else  go v li mi
  else  do
  let
    innermi = mi + boolInt (v <= mi) - boolInt (even $ ri - li)
    lower = v <= innermi
  resp <- if  lower  then  query li innermi  else  query (innermi+1) ri
  if  (resp == v) == lower
    then  go v li innermi
    else  go v (innermi+1) ri

main :: IO ()
main = (P.getContents >>=) . evalStateT $ do
  [n] <- readInts
  sndMin <- query 1 n
  ans <- go sndMin 1 n
  lift $ B.hPutBuilder stdout
    $ B.char7 '!' <> B.char7 ' ' <> B.intDec ans <> B.char7 '\n'

type SIO = StateT P.ByteString IO

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

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

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

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

------

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

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

------

getInt = fst . fromJust . B.readInt . dropCR <$> B.getLine

ask l r = do
  B.putStrLn $ B.unwords ["?", bshow (l + 1), bshow r]
  hFlush stdout
  (subtract 1) <$> getInt

answer i = do
  B.putStrLn $ B.unwords ["!", bshow (i + 1)]
  hFlush stdout

main = do
  n <- getInt
  p <- ask 0 n
  let r = sortOn (\(i, j) -> i - j) $
          filter (\(i, j) -> i /= j) [(0, p), (p + 1, n)]
  case r of
    [(i, j)] -> go p i j
    [(i, j), (k, l)]
      | i < p -> do q <- ask i (p + 1)
                    if p == q
                      then go p i j
                      else go p k l
      | otherwise -> do q <- ask p j
                        if p == q
                          then go p i j
                          else go p k l

go p i j | i < p = lgo i j p
         | otherwise = rgo p i j

lgo i j p | j - i == 1 = answer i
          | otherwise = let k = (i + j) `quot` 2 in
                          do q <- ask k (p + 1)
                             if p == q
                               then lgo k j p
                               else lgo i k p

rgo p i j | j - i == 1 = answer i
          | otherwise = let k = (i + j) `quot` 2 in
                          do q <- ask p k
                             if p == q
                               then rgo p i k
                               else rgo p k j


You are given a weighted undirected graph on n vertices and m edges. Find the shortest path from vertex s to vertex t or else state that such path doesn't exist.

The first line of the input contains two space-separated integers — n and m (1 ≤ n ≤ 105; 0 ≤ m ≤ 105). Next m lines contain the description of the graph edges. The i-th line contains three space-separated integers — ui, vi, xi (1 ≤ ui, vi ≤ n; 0 ≤ xi ≤ 105). That means that vertices with numbers ui and vi are connected by edge of length 2xi (2 to the power of xi). The last line contains two space-separated integers — the numbers of vertices s and t. The vertices are numbered from 1 to n. The graph contains no multiple edges and self-loops.

In the first line print the remainder after dividing the length of the shortest path by 1000000007 (109 + 7) if the path exists, and -1 if the path doesn't exist. If the path exists print in the second line integer k — the number of vertices in the shortest path from vertex s to vertex t; in the third line print k space-separated integers — the vertices of the shortest path in the visiting order. The first vertex should be vertex s, the last vertex should be vertex t. If there are multiple shortest paths, print any of them.

NoteA path from vertex s to vertex t is a sequence v0, ..., vk, such that v0 = s, vk = t, and for any i from 0 to k - 1 vertices vi and vi + 1 are connected by an edge. The length of the path is the sum of weights of edges between vi and vi + 1 for all i from 0 to k - 1. The shortest path from s to t is the path which length is minimum among all possible paths from s to t.

import Data.Word
import Data.Int
import Data.Bits
import Control.Monad
import Control.Applicative
import Control.Arrow
import qualified Data.Set as Set
import qualified Data.Map as Map
import Data.Set(Set)

newtype Mod1b7 = Mod1b7 Int32 deriving (Eq, Ord)

instance Show Mod1b7 where
  show (Mod1b7 x) = show x

moddd :: Num x => x
moddd = 10^9 + 7
instance Num Mod1b7 where
  Mod1b7 x + Mod1b7 y = Mod1b7 ((x + y) `rem` moddd)
  Mod1b7 x * Mod1b7 y = Mod1b7 (fromIntegral ((fromIntegral x * fromIntegral y :: Int64) `rem` moddd))
  fromInteger x = Mod1b7 (fromInteger $ x `mod` moddd)
  negate (Mod1b7 x) = Mod1b7 ((- x) `mod` moddd)

instance Fractional Mod1b7 where
  recip x = x ^ (moddd - 2)

newtype Mod1b9 = Mod1b9 Int64 deriving (Eq, Ord)

instance Show Mod1b9 where
  show (Mod1b9 x) = show x

moddd9 :: Num x => x
moddd9 = 10^9 + 9
instance Num Mod1b9 where
  Mod1b9 x + Mod1b9 y = Mod1b9 ((x + y) `rem` moddd9)
  Mod1b9 x * Mod1b9 y = Mod1b9 (fromIntegral ((fromIntegral x * fromIntegral y :: Int64) `rem` moddd9))
  fromInteger x = Mod1b9 (fromInteger $ x `mod` moddd9)
  negate (Mod1b9 x) = Mod1b9 ((- x) `mod` moddd9)

instance Fractional Mod1b9 where
  recip x = x ^ (moddd9 - 2)

data Hash = Hash {-# UNPACK #-} !Mod1b7 {-# UNPACK #-} !Mod1b9 {-# UNPACK #-} !Mod1b7 {-# UNPACK #-} !Mod1b9 deriving (Eq, Show, Ord)

mkHash (Hash l1h l1g h1 g1) (Hash l2h l2g h2 g2) = Hash (l1h * l2h) (l1g * l2g) (h1 * l1h + h2) (g1 * l1g + g2)

data Tree =
  Leaf !Word64 {- 64 bools -}
  | Node  {-# UNPACK #-} !Hash !Tree !Tree (Bool, Tree {- incremented -})
  deriving Show

primHash = uncurry (Hash (2^64) (2^64)) . (fromIntegral &&& fromIntegral)

hash (Leaf x) = primHash x
hash (Node h _ _ _) = h

node :: Tree -> Tree -> Tree
node t1 t2 =
  let res = Node (mkHash (hash t1) (hash t2)) t1 t2 (doIncrement1 res) in res

fullTree 0 = Leaf 0
fullTree n = let x = fullTree (n - 1) in node x x

toDList (Leaf x) = (x:)
toDList (Node _ a b _) = toDList a . toDList b

toList = ($[]) . toDList

i1k t1 (False, t2) = (False, node t1 t2)
i1k t1 (True, t2) = case increment1 t1 of
  (c, t1) -> (c, node t1 t2)

doIncrement1 :: Tree -> (Bool, Tree)
doIncrement1 (Leaf x) = let x' = x + 1 in (x' < x, Leaf x')
doIncrement1 (Node h t1 t2 _) = i1k t1 (increment1 t2)

increment1 (Leaf x) = doIncrement1 (Leaf x)
increment1 (Node _ _ _ x) = x

increment0 :: Int -> Int -> Tree -> (Bool, Tree)
increment0 capacity index0 (Leaf x) = let x' = x + (2 ^ index0) in (x' < x, Leaf x')
increment0 capacity 0 (Node _ _ _ inced) = inced
increment0 capacity index0 (Node h t1 t2 _) | index0 < capacity `div` 2 =
  i1k t1 (increment0 cap2 index0 t2)
 | otherwise = case increment0 cap2 (index0 - cap2) t1 of
   (c, t1) -> (c, node t1 t2)
 where cap2 = capacity `div` 2

instance Eq Tree where
  Leaf x == Leaf y = x == y
  Node h1 _ _ _ == Node h2 _ _ _ = h1 == h2

myCompare (Leaf a) (Leaf b) = compare a b
myCompare (Node h1 l1 r1 _) (Node h2 l2 r2 _)
    | h1 == h2 = EQ
    | otherwise = case myCompare l1 l2 of
      EQ -> myCompare r1 r2
      LT -> LT
      GT -> GT
-- myCompare _ _ = LT

myCompare2 x y = myCompare x y

instance Ord Tree where
    compare = myCompare2

dijkstra :: (Ord path, Ord road, Eq node, Ord node) =>
  (path -> road -> path)
  -> (node -> [(road, node)])
  -> node
  -> Set (path, [node])
  -> Set node
  -> Maybe (path, [node])
dijkstra append edges destination queue visited =
 case Set.minView queue of
  Nothing -> Nothing
  Just ((path, nodes@(node : _)), queue)
   | node == destination -> Just (path, nodes)
   | Set.member node visited -> dijkstra append edges destination queue visited
   | otherwise ->
    dijkstra append edges destination
     (foldl (\s x -> Set.insert x s) queue [(append path road, node' : nodes)|(road,node') <- edges node])
     (Set.insert node visited)

newtype Road = Road Int deriving (Eq, Ord)

-- levels = reverse $ take (17 - 6) $ drop 1 $ iterate (\(Hash a b) -> Hash (a*a) (b*b)) (Hash (2^64) (2^64))

append :: Tree -> Road -> Tree
append t (Road i) = case increment0 (2 ^ 17) i t of
  (False, t) -> t

readInts = map (foldl (\a x -> a * 10 + (fromEnum x - fromEnum '0')) 0) . words <$> getLine

toMod :: [Word64] -> Mod1b7
toMod = foldl (\a x -> a * (2 ^ 64) + fromIntegral x) 0

pp :: Maybe (Mod1b7, [Int]) -> IO ()
pp Nothing = print (-1)
pp (Just (m, l)) = print m >> print (length l) >> putStrLn (unwords $ map show (reverse l))

main = do
  [n,m] <- readInts
  edges <- replicateM m $ do
    [u,v,x] <- readInts
    return (u,v,x)
  [s,t] <- readInts
  let edgeLists = Map.fromListWith (++) (concat [[(u, [(Road x, v)]), (v, [(Road x, u)])] |(u,v,x) <- edges] ++ [(i,[])|i<-[1..n]])
  pp $ fmap (toMod . toList *** id) $ dijkstra append (edgeLists Map.!) t (Set.singleton (fullTree 11, [s])) Set.empty

et = fullTree 3

import Data.Word
import Data.Int
import Data.Bits
import Control.Monad
import Control.Applicative
import Control.Arrow
import qualified Data.Set as Set
import qualified Data.Map as Map
import Data.Set(Set)

newtype Mod1b7 = Mod1b7 Int32 deriving (Eq, Ord)

instance Show Mod1b7 where
  show (Mod1b7 x) = show x

moddd :: Num x => x
moddd = 10^9 + 7
instance Num Mod1b7 where
  Mod1b7 x + Mod1b7 y = Mod1b7 ((x + y) `rem` moddd)
  Mod1b7 x * Mod1b7 y = Mod1b7 (fromIntegral ((fromIntegral x * fromIntegral y :: Int64) `rem` moddd))
  fromInteger x = Mod1b7 (fromInteger $ x `mod` moddd)
  negate (Mod1b7 x) = Mod1b7 ((- x) `mod` moddd)

instance Fractional Mod1b7 where
  recip x = x ^ (moddd - 2)

newtype Mod1b9 = Mod1b9 Int64 deriving (Eq, Ord)

instance Show Mod1b9 where
  show (Mod1b9 x) = show x

moddd9 :: Num x => x
moddd9 = 10^9 + 9
instance Num Mod1b9 where
  Mod1b9 x + Mod1b9 y = Mod1b9 ((x + y) `rem` moddd9)
  Mod1b9 x * Mod1b9 y = Mod1b9 (fromIntegral ((fromIntegral x * fromIntegral y :: Int64) `rem` moddd9))
  fromInteger x = Mod1b9 (fromInteger $ x `mod` moddd9)
  negate (Mod1b9 x) = Mod1b9 ((- x) `mod` moddd9)

instance Fractional Mod1b9 where
  recip x = x ^ (moddd9 - 2)

data Hash = Hash {-# UNPACK #-} !Mod1b7 {-# UNPACK #-} !Mod1b9 deriving (Eq, Show, Ord)

mkHash (Hash hl gl) (Hash h1 g1) (Hash h2 g2) = Hash (h1 * hl + h2) (g1 * gl + g2)

data Tree =
  Leaf !Word64 {- 64 bools -}
  | Node  {-# UNPACK #-} !Hash !Tree !Tree
  deriving Show

primHash = uncurry Hash . (fromIntegral &&& fromIntegral)

hash (Leaf x) = primHash x
hash (Node h _ _) = h

node :: Hash -> Tree -> Tree -> Tree
node l t1 t2 = Node (mkHash l (hash t1) (hash t2)) t1 t2

fullTree 0 = Leaf 0
fullTree n = let x = fullTree (n - 1) in node (Hash 0 0) x x

toDList (Leaf x) = (x:)
toDList (Node _ a b) = toDList a . toDList b

toList = ($[]) . toDList

div2h = Hash (recip 2) (recip 2)
hd2 (Hash a b) = case div2h of
  (Hash c d) -> Hash (a * c) (b * d)

increment :: [Hash] -> Int -> Int -> Tree -> (Bool, Tree)
increment _levels capacity index (Leaf x) = let x' = x + (2 ^ (capacity - 1 - index)) in (x' < x, Leaf x')
increment (level : levels) capacity index (Node h t1 t2) | index >= capacity `div` 2 = case increment levels (capacity `div` 2) (index - capacity `div` 2) t2 of
  (False, t2) -> (False, node level t1 t2)
  (True, t2) -> case increment levels (capacity `div` 2) (capacity `div` 2 - 1) t1 of
    (c, t1) -> (c, node level t1 t2)
 | otherwise = case increment levels (capacity `div` 2) index t1 of
   (c, t1) -> (c, node level t1 t2)

instance Eq Tree where
  Leaf x == Leaf y = x == y
  Node h1 _ _ == Node h2 _ _ = h1 == h2

myCompare (Leaf a) (Leaf b) = compare a b
myCompare (Node h1 l1 r1) (Node h2 l2 r2)
    | h1 == h2 = EQ
    | otherwise = case myCompare l1 l2 of
      EQ -> myCompare r1 r2
      LT -> LT
      GT -> GT
-- myCompare _ _ = LT

myCompare2 x y = myCompare x y

instance Ord Tree where
    compare = myCompare2

dijkstra :: (Ord path, Ord road, Eq node, Ord node) =>
  (path -> road -> path)
  -> (node -> [(road, node)])
  -> node
  -> Set (path, [node])
  -> Set node
  -> Maybe (path, [node])
dijkstra append edges destination queue visited =
 case Set.minView queue of
  Nothing -> Nothing
  Just ((path, nodes@(node : _)), queue)
   | node == destination -> Just (path, nodes)
   | Set.member node visited -> dijkstra append edges destination queue visited
   | otherwise ->
    dijkstra append edges destination
     (foldl (\s x -> Set.insert x s) queue [(append path road, node' : nodes)|(road,node') <- edges node])
     (Set.insert node visited)

newtype Road = Road Int deriving (Eq, Ord)

levels = reverse $ take (17 - 6) $ drop 1 $ iterate (\(Hash a b) -> Hash (a*a) (b*b)) (Hash (2^64) (2^64))

append :: Tree -> Road -> Tree
append t (Road i) = case increment levels (2 ^ 17) (2 ^ 17 - 1 - i) t of
  (False, t) -> t

readInts = map (foldl (\a x -> a * 10 + (fromEnum x - fromEnum '0')) 0) . words <$> getLine

toMod :: [Word64] -> Mod1b7
toMod = foldl (\a x -> a * (2 ^ 64) + fromIntegral x) 0

pp :: Maybe (Mod1b7, [Int]) -> IO ()
pp Nothing = print (-1)
pp (Just (m, l)) = print m >> print (length l) >> putStrLn (unwords $ map show (reverse l))

main = do
  [n,m] <- readInts
  edges <- replicateM m $ do
    [u,v,x] <- readInts
    return (u,v,x)
  [s,t] <- readInts
  let edgeLists = Map.fromListWith (++) (concat [[(u, [(Road x, v)]), (v, [(Road x, u)])] |(u,v,x) <- edges] ++ [(i,[])|i<-[1..n]])
  pp $ fmap (toMod . toList *** id) $ dijkstra append (edgeLists Map.!) t (Set.singleton (fullTree 11, [s])) Set.empty

et = fullTree 3

{- tr1 = snd $ increment (Hash (2^9) (2^9)) (2^9) (2^9 - 1 - 64) et
tr2 = snd $ increment (Hash (2^9) (2^9)) (2^9) (2^9 - 1 - 7) et -}

import Data.Word
import Data.Int
import Data.Bits
import Control.Monad
import Control.Applicative
import Control.Arrow
import qualified Data.Set as Set
import qualified Data.Map as Map
import Data.Set(Set)

newtype Mod1b7 = Mod1b7 Int32 deriving (Eq, Ord)

instance Show Mod1b7 where
  show (Mod1b7 x) = show x

moddd :: Num x => x
moddd = 10^9 + 7
instance Num Mod1b7 where
  Mod1b7 x + Mod1b7 y = Mod1b7 ((x + y) `rem` moddd)
  Mod1b7 x * Mod1b7 y = Mod1b7 (fromIntegral ((fromIntegral x * fromIntegral y :: Int64) `rem` moddd))
  fromInteger x = Mod1b7 (fromInteger $ x `mod` moddd)
  negate (Mod1b7 x) = Mod1b7 ((- x) `mod` moddd)

instance Fractional Mod1b7 where
  recip x = x ^ (moddd - 2)

newtype Mod1b9 = Mod1b9 Int64 deriving (Eq, Ord)

instance Show Mod1b9 where
  show (Mod1b9 x) = show x

moddd9 :: Num x => x
moddd9 = 10^9 + 9
instance Num Mod1b9 where
  Mod1b9 x + Mod1b9 y = Mod1b9 ((x + y) `rem` moddd9)
  Mod1b9 x * Mod1b9 y = Mod1b9 (fromIntegral ((fromIntegral x * fromIntegral y :: Int64) `rem` moddd9))
  fromInteger x = Mod1b9 (fromInteger $ x `mod` moddd9)
  negate (Mod1b9 x) = Mod1b9 ((- x) `mod` moddd9)

instance Fractional Mod1b9 where
  recip x = x ^ (moddd9 - 2)

data Hash = Hash {-# UNPACK #-} !Mod1b7 {-# UNPACK #-} !Mod1b9 deriving (Eq, Show, Ord)

mkHash (Hash hl gl) (Hash h1 g1) (Hash h2 g2) = Hash (h1 * hl + h2) (g1 * gl + g2)

data Tree =
  Leaf !Word64 {- 64 bools -}
  | Node  {-# UNPACK #-} !Hash !Tree !Tree
  deriving Show

primHash = uncurry Hash . (fromIntegral &&& fromIntegral)

hash (Leaf x) = primHash x
hash (Node h _ _) = h

node :: Hash -> Tree -> Tree -> Tree
node l t1 t2 = Node (mkHash l (hash t1) (hash t2)) t1 t2

inits :: [a] -> [[a]]
inits xs =
  [] : case xs of
    []      -> []
    x : xs' -> map (x :) (inits xs')

p2h n = Hash (2^n) (2^n)

fullTree 0 = Leaf 0
fullTree n = let x = fullTree (n - 1) in node (p2h n) x x

toDList (Leaf x) = (x:)
toDList (Node _ a b) = toDList a . toDList b

toList = ($[]) . toDList

div2h = Hash (recip 2) (recip 2)
hd2 (Hash a b) = case div2h of
  (Hash c d) -> Hash (a * c) (b * d)

increment :: Hash -> Int -> Int -> Tree -> (Bool, Tree)
increment level capacity index (Leaf x) = let x' = x + (2 ^ (capacity - 1 - index)) in (x' < x, Leaf x')
increment level capacity index (Node h t1 t2) | index >= capacity `div` 2 = case increment (hd2 level) (capacity `div` 2) (index - capacity `div` 2) t2 of
  (False, t2) -> (False, node level t1 t2)
  (True, t2) -> case increment level (capacity `div` 2) (capacity `div` 2 - 1) t1 of
    (c, t1) -> (c, node level t1 t2)
 | otherwise = case increment level (capacity `div` 2) index t1 of
   (c, t1) -> (c, node level t1 t2)

instance Eq Tree where
  Leaf x == Leaf y = x == y
  Node h1 _ _ == Node h2 _ _ = h1 == h2
  _ == _ = False

myCompare (Leaf a) (Leaf b) = compare a b
myCompare (Node h1 l1 r1) (Node h2 l2 r2)
    | h1 == h2 = EQ
    | otherwise = case myCompare l1 l2 of
      EQ -> myCompare r1 r2
      LT -> LT
      GT -> GT
-- myCompare _ _ = LT

myCompare2 x y = myCompare x y

instance Ord Tree where
    compare = myCompare2

dijkstra :: (Ord path, Ord road, Eq node, Ord node) =>
  (path -> road -> path) -> (node -> [(road, node)]) -> node -> Set (path, [node]) -> Set node -> Maybe (path, [node])
dijkstra append edges destination queue visited =
    case Set.minView queue of
      Nothing -> Nothing
      Just ((path, nodes@(node : _)), queue)
        | node == destination -> Just (path, nodes)
        | Set.member node visited -> dijkstra append edges destination queue visited
        | otherwise ->
          dijkstra append edges destination
            (foldl (\s x -> Set.insert x s) queue [(append path road, node' : nodes)|(road,node') <- edges node])
            (Set.insert node visited)

newtype Road = Road Int deriving (Eq, Ord)

append :: Tree -> Road -> Tree
append t (Road i) = case increment (Hash (2^17) (2^17)) (2 ^ (17)) (2 ^ (17) - 1 - i) t of
  (False, t) -> t

readInts = map (foldl (\a x -> a * 10 + (fromEnum x - fromEnum '0')) 0) . words <$> getLine

toMod :: [Word64] -> Mod1b7
toMod = foldl (\a x -> a * (2 ^ 64) + fromIntegral x) 0

pp :: Maybe (Mod1b7, [Int]) -> IO ()
pp Nothing = print (-1)
pp (Just (m, l)) = print m >> print (length l) >> putStrLn (unwords $ map show (reverse l))

main = do
  [n,m] <- readInts
  edges <- replicateM m $ do
    [u,v,x] <- readInts
    return (u,v,x)
  [s,t] <- readInts
  let edgeLists = Map.fromListWith (++) (concat [[(u, [(Road x, v)]), (v, [(Road x, u)])] |(u,v,x) <- edges] ++ [(i,[])|i<-[1..n]])
  pp $ fmap (toMod  . toList *** id) $ dijkstra append (edgeLists Map.!) t (Set.singleton (fullTree 11, [s])) Set.empty

import Data.Word
import Data.Int
import Data.Bits
import Control.Monad
import Control.Applicative
import Control.Arrow
import qualified Data.Set as Set
import qualified Data.Map as Map
import Data.Set(Set)

newtype Mod1b7 = Mod1b7 Int64 deriving (Eq, Ord)

instance Show Mod1b7 where
  show (Mod1b7 x) = show x

moddd :: Num x => x
moddd = 10^9 + 7
instance Num Mod1b7 where
  Mod1b7 x + Mod1b7 y = Mod1b7 ((x + y) `mod` moddd)
  Mod1b7 x * Mod1b7 y = Mod1b7 ((x * y) `mod` moddd)
  fromInteger x = Mod1b7 (fromInteger $ x `mod` moddd)
  negate (Mod1b7 x) = Mod1b7 ((- x) `mod` moddd)

instance Fractional Mod1b7 where
  recip x = x ^ (moddd - 2)

data Hash = Hash Int Mod1b7 deriving (Eq, Show, Ord)

mkHash (Hash l1 h1) (Hash l2 h2) = Hash (l1 + l2) (h1 * (2 ^ l1) + h2)

data Tree =
  Leaf !Word64 {- 64 bools -}
  | Node !Hash !Tree !Tree
  deriving Show

primHash = Hash 1 . fromIntegral

hash (Leaf x) = primHash x
hash (Node h _ _) = h

node :: Tree -> Tree -> Tree
node t1 t2 = Node (mkHash (hash t1) (hash t2)) t1 t2

inits :: [a] -> [[a]]
inits xs =
  [] : case xs of
    []      -> []
    x : xs' -> map (x :) (inits xs')

fullTree 0 = Leaf 0
fullTree n = let x = fullTree (n - 1) in node x x

toDList (Leaf x) = (x:)
toDList (Node _ a b) = toDList a . toDList b

toList = ($[]) . toDList

increment :: Int -> Int -> Tree -> (Bool, Tree)
increment capacity index (Leaf x) = let x' = x + (2 ^ (capacity - 1 - index)) in (x' == 0, Leaf x')
increment capacity index (Node h t1 t2) | index >= capacity `div` 2 = case increment  (capacity `div` 2) (index - capacity `div` 2) t2 of
  (False, t2) -> (False, node t1 t2)
  (True, t2) -> case increment  (capacity `div` 2) (capacity `div` 2 - 1) t1 of
    (c, t1) -> (c, node t1 t2)
 | otherwise = case increment (capacity `div` 2) index t1 of
   (c, t1) -> (c, node t1 t2)

instance Eq Tree where
  x == y = compare x y == EQ

myCompare (Leaf a) (Leaf b) = compare a b
myCompare (Node h1 l1 r1) (Node h2 l2 r2)
    | h1 == h2 = EQ
    | otherwise = case myCompare l1 l2 of
      EQ -> myCompare r1 r2
      LT -> LT
      GT -> GT

myCompare2 x y = myCompare x y

instance Ord Tree where
    compare = myCompare2

dijkstra :: (Ord path, Ord road, Eq node, Ord node) =>
  (path -> road -> path) -> (node -> [(road, node)]) -> node -> Set (path, [node]) -> Set node -> Maybe (path, [node])
dijkstra append edges destination queue visited =
    case Set.minView queue of
      Nothing -> Nothing
      Just ((path, nodes@(node : _)), queue)
        | node == destination -> Just (path, nodes)
        | Set.member node visited -> dijkstra append edges destination queue visited
        | otherwise ->
          dijkstra append edges destination
            (foldl (\s x -> Set.insert x s) queue [(append path road, node' : nodes)|(road,node') <- edges node])
            (Set.insert node visited)

newtype Road = Road Int deriving (Eq, Ord)

append :: Tree -> Road -> Tree
append t (Road i) = case increment (2 ^ (17)) (2 ^ (17) - 1 - i) t of
  (False, t) -> t

readInts = map (foldl (\a x -> a * 10 + (fromEnum x - fromEnum '0')) 0) . words <$> getLine

toMod :: [Word64] -> Mod1b7
toMod = foldl (\a x -> a * 2 + fromIntegral x) 0

pp Nothing = print (-1)
pp (Just (m, l)) = print m >> print (length l) >> putStrLn (unwords $ map show (reverse l))

main = do
  [n,m] <- readInts
  edges <- replicateM m $ do
    [u,v,x] <- readInts
    return (u,v,x)
  [s,t] <- readInts
  let edgeLists = Map.fromListWith (++) (concat [[(u, [(Road x, v)]), (v, [(Road x, u)])] |(u,v,x) <- edges] ++ [(i,[])|i<-[1..n]])
  pp $ fmap (toMod  . toList *** id) $ dijkstra append (edgeLists Map.!) t (Set.singleton (fullTree 11, [s])) Set.empty

import Data.Word
import Data.Int
import Data.Bits
import Control.Monad
import Control.Applicative
import Control.Arrow
import qualified Data.Set as Set
import qualified Data.Map as Map
import Data.Set(Set)

newtype Mod1b7 = Mod1b7 Int32 deriving (Eq, Ord)

instance Show Mod1b7 where
  show (Mod1b7 x) = show x

moddd :: Num x => x
moddd = 10^9 + 7
instance Num Mod1b7 where
  Mod1b7 x + Mod1b7 y = Mod1b7 ((x + y) `rem` moddd)
  Mod1b7 x * Mod1b7 y = Mod1b7 (fromIntegral ((fromIntegral x * fromIntegral y :: Int64) `rem` moddd))
  fromInteger x = Mod1b7 (fromInteger $ x `mod` moddd)
  negate (Mod1b7 x) = Mod1b7 ((- x) `mod` moddd)

instance Fractional Mod1b7 where
  recip x = x ^ (moddd - 2)

newtype Mod1b9 = Mod1b9 Int64 deriving (Eq, Ord)

instance Show Mod1b9 where
  show (Mod1b9 x) = show x

moddd9 :: Num x => x
moddd9 = 10^9 + 9
instance Num Mod1b9 where
  Mod1b9 x + Mod1b9 y = Mod1b9 ((x + y) `rem` moddd9)
  Mod1b9 x * Mod1b9 y = Mod1b9 (fromIntegral ((fromIntegral x * fromIntegral y :: Int64) `rem` moddd9))
  fromInteger x = Mod1b9 (fromInteger $ x `mod` moddd9)
  negate (Mod1b9 x) = Mod1b9 ((- x) `mod` moddd9)

instance Fractional Mod1b9 where
  recip x = x ^ (moddd9 - 2)

data Hash = Hash {-# UNPACK #-} !Mod1b7 {-# UNPACK #-} !Mod1b9 deriving (Eq, Show, Ord)

mkHash (Hash hl gl) (Hash h1 g1) (Hash h2 g2) = Hash (h1 * hl + h2) (g1 * gl + g2)

data Tree =
  Leaf !Word64 {- 64 bools -}
  | Node  {-# UNPACK #-} !Hash !Tree !Tree
  deriving Show

primHash = uncurry Hash . (fromIntegral &&& fromIntegral)

hash (Leaf x) = primHash x
hash (Node h _ _) = h

node :: Hash -> Tree -> Tree -> Tree
node l t1 t2 = Node (mkHash l (hash t1) (hash t2)) t1 t2

inits :: [a] -> [[a]]
inits xs =
  [] : case xs of
    []      -> []
    x : xs' -> map (x :) (inits xs')

p2h n = Hash (2^n) (2^n)

fullTree 0 = Leaf 0
fullTree n = let x = fullTree (n - 1) in node (Hash 0 0) x x

toDList (Leaf x) = (x:)
toDList (Node _ a b) = toDList a . toDList b

toList = ($[]) . toDList

div2h = Hash (recip 2) (recip 2)
hd2 (Hash a b) = case div2h of
  (Hash c d) -> Hash (a * c) (b * d)

increment :: Hash -> Int -> Int -> Tree -> (Bool, Tree)
increment level capacity index (Leaf x) = let x' = x + (2 ^ (capacity - 1 - index)) in (x' < x, Leaf x')
increment level capacity index (Node h t1 t2) | index >= capacity `div` 2 = case increment (hd2 level) (capacity `div` 2) (index - capacity `div` 2) t2 of
  (False, t2) -> (False, node level t1 t2)
  (True, t2) -> case increment (hd2 level) (capacity `div` 2) (capacity `div` 2 - 1) t1 of
    (c, t1) -> (c, node level t1 t2)
 | otherwise = case increment (hd2 level) (capacity `div` 2) index t1 of
   (c, t1) -> (c, node level t1 t2)

instance Eq Tree where
  Leaf x == Leaf y = x == y
  Node h1 _ _ == Node h2 _ _ = h1 == h2
  _ == _ = False

myCompare (Leaf a) (Leaf b) = compare a b
myCompare (Node h1 l1 r1) (Node h2 l2 r2)
    | h1 == h2 = EQ
    | otherwise = case myCompare l1 l2 of
      EQ -> myCompare r1 r2
      LT -> LT
      GT -> GT
-- myCompare _ _ = LT

myCompare2 x y = myCompare x y

instance Ord Tree where
    compare = myCompare2

dijkstra :: (Ord path, Ord road, Eq node, Ord node) =>
  (path -> road -> path) -> (node -> [(road, node)]) -> node -> Set (path, [node]) -> Set node -> Maybe (path, [node])
dijkstra append edges destination queue visited =
    case Set.minView queue of
      Nothing -> Nothing
      Just ((path, nodes@(node : _)), queue)
        | node == destination -> Just (path, nodes)
        | Set.member node visited -> dijkstra append edges destination queue visited
        | otherwise ->
          dijkstra append edges destination
            (foldl (\s x -> Set.insert x s) queue [(append path road, node' : nodes)|(road,node') <- edges node])
            (Set.insert node visited)

newtype Road = Road Int deriving (Eq, Ord)

append :: Tree -> Road -> Tree
append t (Road i) = case increment (Hash (2^17) (2^17)) (2 ^ (17)) (2 ^ (17) - 1 - i) t of
  (False, t) -> t

readInts = map (foldl (\a x -> a * 10 + (fromEnum x - fromEnum '0')) 0) . words <$> getLine

toMod :: [Word64] -> Mod1b7
toMod = foldl (\a x -> a * (2 ^ 64) + fromIntegral x) 0

pp :: Maybe (Mod1b7, [Int]) -> IO ()
pp Nothing = print (-1)
pp (Just (m, l)) = print m >> print (length l) >> putStrLn (unwords $ map show (reverse l))

main = do
  [n,m] <- readInts
  edges <- replicateM m $ do
    [u,v,x] <- readInts
    return (u,v,x)
  [s,t] <- readInts
  let edgeLists = Map.fromListWith (++) (concat [[(u, [(Road x, v)]), (v, [(Road x, u)])] |(u,v,x) <- edges] ++ [(i,[])|i<-[1..n]])
  pp $ fmap (toMod  . toList *** id) $ dijkstra append (edgeLists Map.!) t (Set.singleton (fullTree 11, [s])) Set.empty

import Data.Word
import Data.Int
import Data.Bits
import Control.Monad
import Control.Applicative
import Control.Arrow
import qualified Data.Set as Set
import qualified Data.Map as Map
import Data.Set(Set)

newtype Mod1b7 = Mod1b7 Int32 deriving (Eq, Ord)

instance Show Mod1b7 where
  show (Mod1b7 x) = show x

moddd :: Num x => x
moddd = 10^9 + 7
instance Num Mod1b7 where
  Mod1b7 x + Mod1b7 y = Mod1b7 ((x + y) `mod` moddd)
  Mod1b7 x * Mod1b7 y = Mod1b7 (fromIntegral ((fromIntegral x * fromIntegral y :: Int64) `mod` moddd))
  fromInteger x = Mod1b7 (fromInteger $ x `mod` moddd)
  negate (Mod1b7 x) = Mod1b7 ((- x) `mod` moddd)

instance Fractional Mod1b7 where
  recip x = x ^ (moddd - 2)

newtype Mod1b9 = Mod1b9 Int64 deriving (Eq, Ord)

instance Show Mod1b9 where
  show (Mod1b9 x) = show x

moddd9 :: Num x => x
moddd9 = 10^9 + 9
instance Num Mod1b9 where
  Mod1b9 x + Mod1b9 y = Mod1b9 ((x + y) `mod` moddd9)
  Mod1b9 x * Mod1b9 y = Mod1b9 (fromIntegral ((fromIntegral x * fromIntegral y :: Int64) `mod` moddd9))
  fromInteger x = Mod1b9 (fromInteger $ x `mod` moddd9)
  negate (Mod1b9 x) = Mod1b9 ((- x) `mod` moddd9)

instance Fractional Mod1b9 where
  recip x = x ^ (moddd9 - 2)

data Hash = Hash {-# UNPACK #-} !Mod1b7 {-# UNPACK #-} !Mod1b9 deriving (Eq, Show, Ord)

mkHash l (Hash h1 g1) (Hash h2 g2) = Hash (h1 * (2 ^ l) + h2) (g1 * (2 ^ l) + g2)

data Tree =
  Leaf !Word64 {- 64 bools -}
  | Node  {-# UNPACK #-} !Hash !Tree !Tree
  deriving Show

primHash = uncurry Hash . (fromIntegral &&& fromIntegral)

hash (Leaf x) = primHash x
hash (Node h _ _) = h

node :: Int -> Tree -> Tree -> Tree
node l t1 t2 = Node (mkHash l (hash t1) (hash t2)) t1 t2

inits :: [a] -> [[a]]
inits xs =
  [] : case xs of
    []      -> []
    x : xs' -> map (x :) (inits xs')

fullTree 0 = Leaf 0
fullTree n = let x = fullTree (n - 1) in node n x x

toDList (Leaf x) = (x:)
toDList (Node _ a b) = toDList a . toDList b

toList = ($[]) . toDList

increment :: Int -> Int -> Int -> Tree -> (Bool, Tree)
increment level capacity index (Leaf x) = let x' = x + (2 ^ (capacity - 1 - index)) in (x' == 0, Leaf x')
increment level capacity index (Node h t1 t2) | index >= capacity `div` 2 = case increment level (capacity `div` 2) (index - capacity `div` 2) t2 of
  (False, t2) -> (False, node level t1 t2)
  (True, t2) -> case increment level (capacity `div` 2) (capacity `div` 2 - 1) t1 of
    (c, t1) -> (c, node level t1 t2)
 | otherwise = case increment level (capacity `div` 2) index t1 of
   (c, t1) -> (c, node level t1 t2)

instance Eq Tree where
  x == y = compare x y == EQ

myCompare (Leaf a) (Leaf b) = compare a b
myCompare (Node h1 l1 r1) (Node h2 l2 r2)
    | h1 == h2 = EQ
    | otherwise = case myCompare l1 l2 of
      EQ -> myCompare r1 r2
      LT -> LT
      GT -> GT
myCompare _ _ = LT

myCompare2 x y = myCompare x y

instance Ord Tree where
    compare = myCompare2

dijkstra :: (Ord path, Ord road, Eq node, Ord node) =>
  (path -> road -> path) -> (node -> [(road, node)]) -> node -> Set (path, [node]) -> Set node -> Maybe (path, [node])
dijkstra append edges destination queue visited =
    case Set.minView queue of
      Nothing -> Nothing
      Just ((path, nodes@(node : _)), queue)
        | node == destination -> Just (path, nodes)
        | Set.member node visited -> dijkstra append edges destination queue visited
        | otherwise ->
          dijkstra append edges destination
            (foldl (\s x -> Set.insert x s) queue [(append path road, node' : nodes)|(road,node') <- edges node])
            (Set.insert node visited)

newtype Road = Road Int deriving (Eq, Ord)

append :: Tree -> Road -> Tree
append t (Road i) = case increment 17 (2 ^ (17)) (2 ^ (17) - 1 - i) t of
  (False, t) -> t

readInts = map (foldl (\a x -> a * 10 + (fromEnum x - fromEnum '0')) 0) . words <$> getLine

toMod :: [Word64] -> Mod1b7
toMod = foldl (\a x -> a * 2 + fromIntegral x) 0

pp :: Maybe (Mod1b7, [Int]) -> IO ()
pp Nothing = print (-1)
pp (Just (m, l)) = print m >> print (length l) >> putStrLn (unwords $ map show (reverse l))

main = do
  [n,m] <- readInts
  edges <- replicateM m $ do
    [u,v,x] <- readInts
    return (u,v,x)
  [s,t] <- readInts
  let edgeLists = Map.fromListWith (++) (concat [[(u, [(Road x, v)]), (v, [(Road x, u)])] |(u,v,x) <- edges] ++ [(i,[])|i<-[1..n]])
  pp $ fmap (toMod  . toList *** id) $ dijkstra append (edgeLists Map.!) t (Set.singleton (fullTree 11, [s])) Set.empty

import Data.Word
import Data.Int
import Data.Bits
import Control.Monad
import Control.Applicative
import Control.Arrow
import qualified Data.Set as Set
import qualified Data.Map as Map
import Data.Set(Set)

newtype Mod1b7 = Mod1b7 Int64 deriving (Eq, Ord)

instance Show Mod1b7 where
  show (Mod1b7 x) = show x

moddd :: Num x => x
moddd = 10^9 + 7
instance Num Mod1b7 where
  Mod1b7 x + Mod1b7 y = Mod1b7 ((x + y) `mod` moddd)
  Mod1b7 x * Mod1b7 y = Mod1b7 ((x * y) `mod` moddd)
  fromInteger x = Mod1b7 (fromInteger $ x `mod` moddd)
  negate (Mod1b7 x) = Mod1b7 ((- x) `mod` moddd)

instance Fractional Mod1b7 where
  recip x = x ^ (moddd - 2)

data Hash = Hash Int Mod1b7 deriving (Eq, Show, Ord)

mkHash (Hash l1 h1) (Hash l2 h2) = Hash (l1 + l2) (h1 * (2 ^ l1) + h2)

data Tree =
  Leaf !Word64 {- 64 bools -}
  | Node !Hash !Tree !Tree
  deriving Show

primHash = Hash 1 . fromIntegral

hash (Leaf x) = primHash x
hash (Node h _ _) = h

node :: Tree -> Tree -> Tree
node t1 t2 = Node (mkHash (hash t1) (hash t2)) t1 t2

inits :: [a] -> [[a]]
inits xs =
  [] : case xs of
    []      -> []
    x : xs' -> map (x :) (inits xs')

fullTree 0 = Leaf 0
fullTree n = let x = fullTree (n - 1) in node x x

toDList (Leaf x) = (x:)
toDList (Node _ a b) = toDList a . toDList b

toList = ($[]) . toDList

increment :: Int -> Int -> Tree -> (Bool, Tree)
increment capacity index (Leaf x) = let x' = x + (2 ^ (capacity - 1 - index)) in (x' == 0, Leaf x')
increment capacity index (Node h t1 t2) | index >= capacity `div` 2 = case increment  (capacity `div` 2) (index - capacity `div` 2) t2 of
  (False, t2) -> (False, node t1 t2)
  (True, t2) -> case increment  (capacity `div` 2) (capacity `div` 2 - 1) t1 of
    (c, t1) -> (c, node t1 t2)
 | otherwise = case increment (capacity `div` 2) index t1 of
   (c, t1) -> (c, node t1 t2)

instance Eq Tree where
  x == y = compare x y == EQ

myCompare (Leaf a) (Leaf b) = compare a b
myCompare (Node h1 l1 r1) (Node h2 l2 r2)
    | h1 == h2 = EQ
    | otherwise = case myCompare l1 l2 of
      EQ -> myCompare r1 r2
      LT -> LT
      GT -> GT

myCompare2 x y = myCompare x y

instance Ord Tree where
    compare = myCompare2

dijkstra :: (Ord path, Ord road, Eq node, Ord node) =>
  (path -> road -> path) -> (node -> [(road, node)]) -> node -> Set (path, [node]) -> Set node -> Maybe (path, [node])
dijkstra append edges destination queue visited =
    case Set.minView queue of
      Nothing -> Nothing
      Just ((path, nodes@(node : _)), queue)
        | node == destination -> Just (path, nodes)
        | Set.member node visited -> dijkstra append edges destination queue visited
        | otherwise ->
          dijkstra append edges destination
            (foldl (\s x -> Set.insert x s) queue [(append path road, node' : nodes)|(road,node') <- edges node])
            (Set.insert node visited)

newtype Road = Road Int deriving (Eq, Ord)

append :: Tree -> Road -> Tree
append t (Road i) = case increment (2 ^ (17)) (2 ^ (17) - 1 - i) t of
  (False, t) -> t

readInts = map (foldl (\a x -> a * 10 + (fromEnum x - fromEnum '0')) 0) . words <$> getLine

toMod :: [Word64] -> Mod1b7
toMod = foldl (\a x -> a * 2 + fromIntegral x) 0

pp Nothing = print (-1)
pp (Just (m, l)) = print m >> print (length l) >> putStrLn (unwords $ map show (reverse l))

main = do
  [n,m] <- readInts
  edges <- replicateM m $ do
    [u,v,x] <- readInts
    return (u,v,x)
  [s,t] <- readInts
  print "hi"
  let edgeLists = Map.fromListWith (++) (concat [[(u, [(Road x, v)]), (v, [(Road x, u)])] |(u,v,x) <- edges] ++ [(i,[])|i<-[1..n]])
  pp $ fmap (toMod  . toList *** id) $ dijkstra append (edgeLists Map.!) t (Set.singleton (fullTree 11, [s])) Set.empty

import Data.Word
import Data.Int
import Data.Bits
import Control.Monad
import Control.Applicative
import Control.Arrow
import qualified Data.Set as Set
import qualified Data.Map as Map
import Data.Set(Set)

newtype Mod1b7 = Mod1b7 Int32 deriving (Eq, Ord)

instance Show Mod1b7 where
  show (Mod1b7 x) = show x

moddd :: Num x => x
moddd = 10^9 + 7
instance Num Mod1b7 where
  Mod1b7 x + Mod1b7 y = Mod1b7 ((x + y) `rem` moddd)
  Mod1b7 x * Mod1b7 y = Mod1b7 (fromIntegral ((fromIntegral x * fromIntegral y :: Int64) `rem` moddd))
  fromInteger x = Mod1b7 (fromInteger $ x `mod` moddd)
  negate (Mod1b7 x) = Mod1b7 ((- x) `mod` moddd)

instance Fractional Mod1b7 where
  recip x = x ^ (moddd - 2)

newtype Mod1b9 = Mod1b9 Int64 deriving (Eq, Ord)

instance Show Mod1b9 where
  show (Mod1b9 x) = show x

moddd9 :: Num x => x
moddd9 = 10^9 + 9
instance Num Mod1b9 where
  Mod1b9 x + Mod1b9 y = Mod1b9 ((x + y) `rem` moddd9)
  Mod1b9 x * Mod1b9 y = Mod1b9 (fromIntegral ((fromIntegral x * fromIntegral y :: Int64) `rem` moddd9))
  fromInteger x = Mod1b9 (fromInteger $ x `mod` moddd9)
  negate (Mod1b9 x) = Mod1b9 ((- x) `mod` moddd9)

instance Fractional Mod1b9 where
  recip x = x ^ (moddd9 - 2)

data Hash = Hash {-# UNPACK #-} !Mod1b7 {-# UNPACK #-} !Mod1b9 deriving (Eq, Show, Ord)

mkHash (Hash hl gl) (Hash h1 g1) (Hash h2 g2) = Hash (h1 * hl + h2) (g1 * gl + g2)

data Tree =
  Leaf !Word64 {- 64 bools -}
  | Node  {-# UNPACK #-} !Hash !Tree !Tree
  deriving Show

primHash = uncurry Hash . (fromIntegral &&& fromIntegral)

hash (Leaf x) = primHash x
hash (Node h _ _) = h

node :: Hash -> Tree -> Tree -> Tree
node l t1 t2 = Node (mkHash l (hash t1) (hash t2)) t1 t2

inits :: [a] -> [[a]]
inits xs =
  [] : case xs of
    []      -> []
    x : xs' -> map (x :) (inits xs')

p2h n = Hash (2^n) (2^n)

fullTree 0 = Leaf 0
fullTree n = let x = fullTree (n - 1) in node (p2h n) x x

toDList (Leaf x) = (x:)
toDList (Node _ a b) = toDList a . toDList b

toList = ($[]) . toDList

div2h = Hash (recip 2) (recip 2)
hd2 (Hash a b) = case div2h of
  (Hash c d) -> Hash (a * c) (b * d)

increment :: Hash -> Int -> Int -> Tree -> (Bool, Tree)
increment level capacity index (Leaf x) = let x' = x + (2 ^ (capacity - 1 - index)) in (x' == 0, Leaf x')
increment level capacity index (Node h t1 t2) | index >= capacity `div` 2 = case increment (hd2 level) (capacity `div` 2) (index - capacity `div` 2) t2 of
  (False, t2) -> (False, node level t1 t2)
  (True, t2) -> case increment level (capacity `div` 2) (capacity `div` 2 - 1) t1 of
    (c, t1) -> (c, node level t1 t2)
 | otherwise = case increment level (capacity `div` 2) index t1 of
   (c, t1) -> (c, node level t1 t2)

instance Eq Tree where
  Leaf x == Leaf y = x == y
  Node h1 _ _ == Node h2 _ _ = h1 == h2
  _ == _ = False

myCompare (Leaf a) (Leaf b) = compare a b
myCompare (Node h1 l1 r1) (Node h2 l2 r2)
    | h1 == h2 = EQ
    | otherwise = case myCompare l1 l2 of
      EQ -> myCompare r1 r2
      LT -> LT
      GT -> GT
-- myCompare _ _ = LT

myCompare2 x y = myCompare x y

instance Ord Tree where
    compare = myCompare2

dijkstra :: (Ord path, Ord road, Eq node, Ord node) =>
  (path -> road -> path) -> (node -> [(road, node)]) -> node -> Set (path, [node]) -> Set node -> Maybe (path, [node])
dijkstra append edges destination queue visited =
    case Set.minView queue of
      Nothing -> Nothing
      Just ((path, nodes@(node : _)), queue)
        | node == destination -> Just (path, nodes)
        | Set.member node visited -> dijkstra append edges destination queue visited
        | otherwise ->
          dijkstra append edges destination
            (foldl (\s x -> Set.insert x s) queue [(append path road, node' : nodes)|(road,node') <- edges node])
            (Set.insert node visited)

newtype Road = Road Int deriving (Eq, Ord)

append :: Tree -> Road -> Tree
append t (Road i) = case increment (Hash (2^17) (2^17)) (2 ^ (17)) (2 ^ (17) - 1 - i) t of
  (False, t) -> t

readInts = map (foldl (\a x -> a * 10 + (fromEnum x - fromEnum '0')) 0) . words <$> getLine

toMod :: [Word64] -> Mod1b7
toMod = foldl (\a x -> a * 2 + fromIntegral x) 0

pp :: Maybe (Mod1b7, [Int]) -> IO ()
pp Nothing = print (-1)
pp (Just (m, l)) = print m >> print (length l) >> putStrLn (unwords $ map show (reverse l))

main = do
  [n,m] <- readInts
  edges <- replicateM m $ do
    [u,v,x] <- readInts
    return (u,v,x)
  [s,t] <- readInts
  let edgeLists = Map.fromListWith (++) (concat [[(u, [(Road x, v)]), (v, [(Road x, u)])] |(u,v,x) <- edges] ++ [(i,[])|i<-[1..n]])
  pp $ fmap (toMod  . toList *** id) $ dijkstra append (edgeLists Map.!) t (Set.singleton (fullTree 11, [s])) Set.empty

import Data.Word
import Data.Int
import Data.Bits
import Control.Monad
import Control.Applicative
import Control.Arrow
import qualified Data.Set as Set
import qualified Data.Map as Map
import Data.Set(Set)

newtype Mod1b7 = Mod1b7 Int64 deriving (Eq, Ord)

instance Show Mod1b7 where
  show (Mod1b7 x) = show x

moddd :: Num x => x
moddd = 10^9 + 7
instance Num Mod1b7 where
  Mod1b7 x + Mod1b7 y = Mod1b7 ((x + y) `mod` moddd)
  Mod1b7 x * Mod1b7 y = Mod1b7 ((x * y) `mod` moddd)
  fromInteger x = Mod1b7 (fromInteger $ x `mod` moddd)
  negate (Mod1b7 x) = Mod1b7 ((- x) `mod` moddd)

instance Fractional Mod1b7 where
  recip x = x ^ (moddd - 2)

data Hash = Hash {-# UNPACK #-} !Mod1b7 deriving (Eq, Show, Ord)

mkHash l (Hash h1) (Hash h2) = Hash (h1 * (2 ^ l) + h2)

data Tree =
  Leaf !Word64 {- 64 bools -}
  | Node  {-# UNPACK #-} !Hash !Tree !Tree
  deriving Show

primHash = Hash . fromIntegral

hash (Leaf x) = primHash x
hash (Node h _ _) = h

node :: Int -> Tree -> Tree -> Tree
node l t1 t2 = Node (mkHash l (hash t1) (hash t2)) t1 t2

inits :: [a] -> [[a]]
inits xs =
  [] : case xs of
    []      -> []
    x : xs' -> map (x :) (inits xs')

fullTree 0 = Leaf 0
fullTree n = let x = fullTree (n - 1) in node n x x

toDList (Leaf x) = (x:)
toDList (Node _ a b) = toDList a . toDList b

toList = ($[]) . toDList

increment :: Int -> Int -> Int -> Tree -> (Bool, Tree)
increment level capacity index (Leaf x) = let x' = x + (2 ^ (capacity - 1 - index)) in (x' == 0, Leaf x')
increment level capacity index (Node h t1 t2) | index >= capacity `div` 2 = case increment level (capacity `div` 2) (index - capacity `div` 2) t2 of
  (False, t2) -> (False, node level t1 t2)
  (True, t2) -> case increment level (capacity `div` 2) (capacity `div` 2 - 1) t1 of
    (c, t1) -> (c, node level t1 t2)
 | otherwise = case increment level (capacity `div` 2) index t1 of
   (c, t1) -> (c, node level t1 t2)

instance Eq Tree where
  x == y = compare x y == EQ

myCompare (Leaf a) (Leaf b) = compare a b
myCompare (Node h1 l1 r1) (Node h2 l2 r2)
    | h1 == h2 = EQ
    | otherwise = case myCompare l1 l2 of
      EQ -> myCompare r1 r2
      LT -> LT
      GT -> GT
myCompare _ _ = LT

myCompare2 x y = myCompare x y

instance Ord Tree where
    compare = myCompare2

dijkstra :: (Ord path, Ord road, Eq node, Ord node) =>
  (path -> road -> path) -> (node -> [(road, node)]) -> node -> Set (path, [node]) -> Set node -> Maybe (path, [node])
dijkstra append edges destination queue visited =
    case Set.minView queue of
      Nothing -> Nothing
      Just ((path, nodes@(node : _)), queue)
        | node == destination -> Just (path, nodes)
        | Set.member node visited -> dijkstra append edges destination queue visited
        | otherwise ->
          dijkstra append edges destination
            (foldl (\s x -> Set.insert x s) queue [(append path road, node' : nodes)|(road,node') <- edges node])
            (Set.insert node visited)

newtype Road = Road Int deriving (Eq, Ord)

append :: Tree -> Road -> Tree
append t (Road i) = case increment 17 (2 ^ (17)) (2 ^ (17) - 1 - i) t of
  (False, t) -> t

readInts = map (foldl (\a x -> a * 10 + (fromEnum x - fromEnum '0')) 0) . words <$> getLine

toMod :: [Word64] -> Mod1b7
toMod = foldl (\a x -> a * 2 + fromIntegral x) 0

pp :: Maybe (Mod1b7, [Int]) -> IO ()
pp Nothing = print (-1)
pp (Just (m, l)) = print m >> print (length l) >> putStrLn (unwords $ map show (reverse l))

main = do
  [n,m] <- readInts
  edges <- replicateM m $ do
    [u,v,x] <- readInts
    return (u,v,x)
  [s,t] <- readInts
  let edgeLists = Map.fromListWith (++) (concat [[(u, [(Road x, v)]), (v, [(Road x, u)])] |(u,v,x) <- edges] ++ [(i,[])|i<-[1..n]])
  pp $ fmap (toMod  . toList *** id) $ dijkstra append (edgeLists Map.!) t (Set.singleton (fullTree 11, [s])) Set.empty

import Data.Word
import Data.Int
import Data.Bits
import Control.Monad
import Control.Applicative
import Control.Arrow
import qualified Data.Set as Set
import qualified Data.Map as Map
import Data.Set(Set)

newtype Mod1b7 = Mod1b7 Int32 deriving (Eq, Ord)

instance Show Mod1b7 where
  show (Mod1b7 x) = show x

moddd :: Num x => x
moddd = 10^9 + 7
instance Num Mod1b7 where
  Mod1b7 x + Mod1b7 y = Mod1b7 ((x + y) `rem` moddd)
  Mod1b7 x * Mod1b7 y = Mod1b7 (fromIntegral ((fromIntegral x * fromIntegral y :: Int64) `rem` moddd))
  fromInteger x = Mod1b7 (fromInteger $ x `mod` moddd)
  negate (Mod1b7 x) = Mod1b7 ((- x) `mod` moddd)

instance Fractional Mod1b7 where
  recip x = x ^ (moddd - 2)

newtype Mod1b9 = Mod1b9 Int64 deriving (Eq, Ord)

instance Show Mod1b9 where
  show (Mod1b9 x) = show x

moddd9 :: Num x => x
moddd9 = 10^9 + 9
instance Num Mod1b9 where
  Mod1b9 x + Mod1b9 y = Mod1b9 ((x + y) `rem` moddd9)
  Mod1b9 x * Mod1b9 y = Mod1b9 (fromIntegral ((fromIntegral x * fromIntegral y :: Int64) `rem` moddd9))
  fromInteger x = Mod1b9 (fromInteger $ x `mod` moddd9)
  negate (Mod1b9 x) = Mod1b9 ((- x) `mod` moddd9)

instance Fractional Mod1b9 where
  recip x = x ^ (moddd9 - 2)

data Hash = Hash {-# UNPACK #-} !Mod1b7 {-# UNPACK #-} !Mod1b9 {-# UNPACK #-} !Mod1b7 {-# UNPACK #-} !Mod1b9 deriving (Eq, Show, Ord)

mkHash (Hash l1h l1g h1 g1) (Hash l2h l2g h2 g2) = Hash (l1h * l2h) (l1g * l2g) (h1 * l1h + h2) (g1 * l1g + g2)

data Tree =
  Leaf !Word64 {- 64 bools -}
  | Node  {-# UNPACK #-} !Hash !Tree !Tree (Bool, Tree {- incremented -})
  deriving Show

primHash = uncurry (Hash 2 2) . (fromIntegral &&& fromIntegral)

hash (Leaf x) = primHash x
hash (Node h _ _ _) = h

node :: Tree -> Tree -> Tree
node t1 t2 =
  let res = Node (mkHash (hash t1) (hash t2)) t1 t2 (doIncrement1 res) in res

fullTree 0 = Leaf 0
fullTree n = let x = fullTree (n - 1) in node x x

toDList (Leaf x) = (x:)
toDList (Node _ a b _) = toDList a . toDList b

toList = ($[]) . toDList

i1k t1 (False, t2) = (False, node t1 t2)
i1k t1 (True, t2) = case increment1 t1 of
  (c, t1) -> (c, node t1 t2)

doIncrement1 :: Tree -> (Bool, Tree)
doIncrement1 (Leaf x) = let x' = x + 1 in (x' < x, Leaf x')
doIncrement1 (Node h t1 t2 _) = i1k t1 (increment1 t2)

increment1 (Leaf x) = doIncrement1 (Leaf x)
increment1 (Node _ _ _ x) = x

increment0 :: Int -> Int -> Tree -> (Bool, Tree)
increment0 capacity index0 (Leaf x) = let x' = x + (2 ^ index0) in (x' < x, Leaf x')
increment0 capacity 0 (Node _ _ _ inced) = inced
increment0 capacity index0 (Node h t1 t2 _) | index0 < capacity `div` 2 =
  i1k t1 (increment0 cap2 index0 t2)
 | otherwise = case increment0 cap2 (index0 - cap2) t1 of
   (c, t1) -> (c, node t1 t2)
 where cap2 = capacity `div` 2

instance Eq Tree where
  Leaf x == Leaf y = x == y
  Node h1 _ _ _ == Node h2 _ _ _ = h1 == h2

myCompare (Leaf a) (Leaf b) = compare a b
myCompare (Node h1 l1 r1 _) (Node h2 l2 r2 _)
    | h1 == h2 = EQ
    | otherwise = case myCompare l1 l2 of
      EQ -> myCompare r1 r2
      LT -> LT
      GT -> GT
-- myCompare _ _ = LT

myCompare2 x y = myCompare x y

instance Ord Tree where
    compare = myCompare2

dijkstra :: (Ord path, Ord road, Eq node, Ord node) =>
  (path -> road -> path)
  -> (node -> [(road, node)])
  -> node
  -> Set (path, [node])
  -> Set node
  -> Maybe (path, [node])
dijkstra append edges destination queue visited =
 case Set.minView queue of
  Nothing -> Nothing
  Just ((path, nodes@(node : _)), queue)
   | node == destination -> Just (path, nodes)
   | Set.member node visited -> dijkstra append edges destination queue visited
   | otherwise ->
    dijkstra append edges destination
     (foldl (\s x -> Set.insert x s) queue [(append path road, node' : nodes)|(road,node') <- edges node])
     (Set.insert node visited)

newtype Road = Road Int deriving (Eq, Ord)

-- levels = reverse $ take (17 - 6) $ drop 1 $ iterate (\(Hash a b) -> Hash (a*a) (b*b)) (Hash (2^64) (2^64))

append :: Tree -> Road -> Tree
append t (Road i) = case increment0 (2 ^ 17) i t of
  (False, t) -> t

readInts = map (foldl (\a x -> a * 10 + (fromEnum x - fromEnum '0')) 0) . words <$> getLine

toMod :: [Word64] -> Mod1b7
toMod = foldl (\a x -> a * (2 ^ 64) + fromIntegral x) 0

pp :: Maybe (Mod1b7, [Int]) -> IO ()
pp Nothing = print (-1)
pp (Just (m, l)) = print m >> print (length l) >> putStrLn (unwords $ map show (reverse l))

main = do
  [n,m] <- readInts
  edges <- replicateM m $ do
    [u,v,x] <- readInts
    return (u,v,x)
  [s,t] <- readInts
  let edgeLists = Map.fromListWith (++) (concat [[(u, [(Road x, v)]), (v, [(Road x, u)])] |(u,v,x) <- edges] ++ [(i,[])|i<-[1..n]])
  pp $ fmap (toMod . toList *** id) $ dijkstra append (edgeLists Map.!) t (Set.singleton (fullTree 11, [s])) Set.empty

et = fullTree 3