Problem:
Score : 700 points

Problem Statement

You are given a simple connected undirected graph with N vertices and M edges. The vertices are numbered 1 to N, and the i-th edge connects Vertex A_i and Vertex B_i.
Takahashi will assign one of the two possible directions to each of the edges in the graph to make a directed graph.
Determine if it is possible to make a directed graph with an even number of edges going out from every vertex. If the answer is yes, construct one such graph.

Notes

An undirected graph is said to be simple when it contains no self-loops or multiple edges.

Constraints

2 \leq N \leq 10^5

N-1 \leq M \leq 10^5

1 \leq A_i,B_i \leq N (1\leq i\leq M)

The given graph is simple and connected.

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
:
A_M B_M

Output

If it is impossible to assign directions to satisfy the requirement, print -1.
Otherwise, print an assignment of directions that satisfies the requirement, in the following format:

C_1 D_1
:
C_M D_M

Here each pair (C_i, D_i) means that there is an edge directed from Vertex C_i to Vertex D_i. The edges may be printed in any order.

Sample Input 1

4 4
1 2
2 3
3 4
4 1

Sample Output 1

1 2
1 4
3 2
3 4

After this assignment of directions, Vertex 1 and 3 will each have two outgoing edges, and Vertex 2 and 4 will each have zero outgoing edges.

Sample Input 2

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

Sample Output 2

-1

Solution in Haskell (GHC 7.10.3) (judge verdict: Accepted)

{-# LANGUAGE
  ScopedTypeVariables, BangPatterns, TupleSections, ExplicitForAll,
  LambdaCase, MultiWayIf, Unsafe, RecordWildCards, FlexibleContexts, CPP,
  NoMonomorphismRestriction, GADTs, PatternGuards, MagicHash, UnboxedTuples,
  RankNTypes, EmptyDataDecls, EmptyCase, ViewPatterns, PolyKinds,
  TypeFamilies #-}
{-# OPTIONS_GHC -O2 #-}

import Prelude
import Data.Bits
import Data.List
import Data.Maybe
import Data.Tuple
import Data.Ord
import Data.Int
import Data.Word
import Data.Char
import Data.Ratio
import Data.Function
import Data.STRef
import Data.IORef
import Data.Monoid
import Data.Functor
import System.IO
import Control.Arrow
import Control.Applicative
import Control.Monad
import Control.Monad.Primitive
import Control.Monad.State.Strict
import Control.Monad.ST
import Control.Monad.ST.Lazy (strictToLazyST, lazyToStrictST)
import qualified Control.Monad.ST.Lazy as STL
-- import Control.Monad.ST.Safe
import Control.DeepSeq
import Data.Coerce
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as BSL
import qualified Data.ByteString.Builder as BSB
import Data.IntMap (IntMap)
import qualified Data.IntMap.Strict as IMS
import qualified Data.IntMap.Lazy as IML
import Data.IntSet (IntSet)
import qualified Data.IntSet as IS
import qualified Data.Sequence as Seq
import Data.Sequence (Seq)
import qualified Data.Array.IArray as A
import qualified Data.Array.MArray.Safe as A
import qualified Data.Array.MArray as A
import Data.Array (Array)
import Data.Array.Unboxed (UArray)
import Data.Array.IArray (IArray)
import Data.Array.MArray.Safe (MArray)
import Data.Array.IO.Safe (IOArray, IOUArray)
import Data.Array.ST.Safe (STArray, STUArray, runSTArray, runSTUArray)
import qualified Data.Vector as V
import qualified Data.Vector.Mutable as VM
import qualified Data.Vector.Unboxed as VU
import qualified Data.Vector.Unboxed.Mutable as VUM
import qualified Data.Vector.Storable as VS
import qualified Data.Vector.Storable.Mutable as VSM
import qualified Data.Vector.Primitive as VP
import qualified Data.Vector.Primitive.Mutable as VPM
import qualified Data.Vector.Generic as VG
import qualified Data.Vector.Generic.Mutable as VGM
import qualified Data.Attoparsec.ByteString.Char8 as Atto
import Debug.Trace
import GHC.Exts (build, Int(..), Int#,
                 (+#), (*#), (-#), (<#), (>=#), (==#), quotRemInt#,
                 remInt#, uncheckedIShiftRL#, andI#, orI#,
                isTrue#)


type Vertex = Int
data GraphData d = GraphData {-# UNPACK #-} !(VU.Vector (Vertex,d))
                             {-# UNPACK #-} !(VU.Vector Int)
data MGraphData s d = MGraphData {-# UNPACK #-} !(VUM.MVector s (Vertex,d))
                                 {-# UNPACK #-} !(VU.Vector Int)
data TreeData d = TreeData {-# UNPACK #-} !Vertex
                           {-# UNPACK #-} !(GraphData d)

doRead :: StateT BSL.ByteString (ST s) (Int,Int,())
doRead = do
  liftA3 (,,)
    (fmap (subtract 1) $ state $ fromJust . BSL.readInt . BSL.dropWhile (<'!'))
    (fmap (subtract 1) $ state $ fromJust . BSL.readInt . BSL.dropWhile (<'!'))
    (return ())

main :: IO ()
main = do
  [n,m] <- map readInt . words <$> getLine
  gr <- do
    inputRest <- BSL.getContents
    return $! runST
      $ (`evalStateT` inputRest) $ getUndirectedGraph n m doRead
  if odd m then print (-1) else do
  visitArr <- VUM.replicate n 0
  let dfs from this = do
        whenM ((>0) <$> VUM.read visitArr this) $ error "IMPOSSIBLE"
        VUM.write visitArr this (1::Int)
        res <- VU.foldM'
          (\ !parity (!v1,()) ->
              if v1 == from then return parity else do
                visitV1 <- VUM.read visitArr v1
                case visitV1 of
                  0 -> do
                    res <- not <$> dfs this v1
                    putStrLn
                      $ if res
                        then shows (this+1) $ ' ' : show (v1+1)
                        else shows (v1+1)   $ ' ' : show (this+1)
                    return (parity `xor` res)
                  1 -> do
                    putStrLn $ shows (this+1) $ ' ' : show (v1+1)
                    return (not parity)
                  2 -> return parity)
          False (edgesOut gr this)
        VUM.write visitArr this 2
        return res
  dfs (-1) 0
  return ()
                    
                     
  


parentInTree :: (VU.Unbox d)
  => TreeData d -> Vertex -> Maybe (Vertex,d)
parentInTree (TreeData root (GraphData connTable degCount)) vert
  | vert == root = Nothing
  | otherwise    = Just $! connTable VU.! (degCount VU.! vert)

childrenInTree :: (VU.Unbox d)
  => TreeData d -> Vertex -> VU.Vector (Vertex,d)
childrenInTree (TreeData root (GraphData connTable degCount)) vert
  = VU.slice beg (end-beg) connTable
  where
    !end = degCount VU.! (vert+1)
    !beg | vert == root = degCount VU.! vert
         | otherwise    = 1 + degCount VU.! vert

edgesOut :: (VU.Unbox d)
  => GraphData d -> Vertex -> VU.Vector (Vertex,d)
edgesOut (GraphData connTable degCount) vert
  = VU.slice beg (end-beg) connTable
  where
    !end = degCount VU.! (vert+1)
    !beg = degCount VU.! vert

type Depth = Int
{-# INLINE getTreeWithDepths #-}
getTreeWithDepths :: (PrimMonad m, VU.Unbox d)
  => Int -> Vertex -> (m (Int,Int,d)) -> m (TreeData d,VU.Vector Depth)
getTreeWithDepths !numVert !root getEdge = do
  !gd <- getUndirectedGraphMut numVert (numVert-1) getEdge
  !depths <- dfsFindTreeAndDepthInMGraph gd root
  !gdFrozen <- unsafeFreezeGraphData gd
  return (TreeData root gdFrozen, depths)

dfsFindTreeAndDepthInMGraph :: (PrimMonad m, VU.Unbox d)
  => MGraphData (PrimState m) d -> Vertex -> m (VU.Vector Depth)
dfsFindTreeAndDepthInMGraph (MGraphData connTable degCount) !root = do
  depths <- VUM.replicate (VU.length degCount - 1) (-1)
  let dfs !parent !this !depth = do
        !prevDepth <- VUM.read depths this
        when (prevDepth < 0) $ do
          VUM.unsafeWrite depths this depth
          let !beg = VU.unsafeIndex degCount this
              !end = VU.unsafeIndex degCount (this+1) - 1
          forM_ [beg..end] $ \ !i -> do
            (!vertex,!d) <- VUM.read connTable i
            if vertex == parent
              then do !vbeg <- VUM.unsafeRead connTable beg
                      VUM.unsafeWrite connTable beg (vertex,d)
                      VUM.unsafeWrite connTable i vbeg
              else dfs this vertex (depth+1)
  dfs (-1) root 0
  VU.unsafeFreeze depths

{-# INLINE unsafeFreezeGraphData #-}
unsafeFreezeGraphData :: (PrimMonad m, VU.Unbox d) =>
  MGraphData (PrimState m) d -> m (GraphData d)
unsafeFreezeGraphData (MGraphData connTable degCount)
  = (`GraphData` degCount) <$!> VU.unsafeFreeze connTable 

{-# INLINE getDirectedGraphBidir #-}
getDirectedGraphBidir :: (PrimMonad m, VU.Unbox d)
  => Int -> Int -> (m (Int,Int,d))
  -> m (GraphData d, GraphData d)
getDirectedGraphBidir !numVert !numEdges getEdge = do
  (!forward,!backward) <- getDirectedGraphMutBidir numVert numEdges getEdge
  !forwardImmut <- unsafeFreezeGraphData forward
  !backwardImmut <- unsafeFreezeGraphData backward
  return $! (forwardImmut, backwardImmut)

{-# INLINE getDirectedGraphForward #-}
getDirectedGraphForward :: (PrimMonad m, VU.Unbox d) =>
  Int -> Int -> m (Int,Int,d) -> m (GraphData d)
getDirectedGraphForward !numVert !numEdges getEdge = do
  getDirectedGraphMutForward numVert numEdges getEdge >>= unsafeFreezeGraphData


{-# INLINE getUndirectedGraph #-}
getUndirectedGraph
  :: (PrimMonad m, VU.Unbox d) =>
  Int -> Int -> (m (Int,Int,d)) -> m (GraphData d)
getUndirectedGraph !numVert !numEdges getEdge
  = getUndirectedGraphMut numVert numEdges getEdge >>= unsafeFreezeGraphData

{-# INLINE getUndirectedGraphMut #-}
getUndirectedGraphMut
  :: (PrimMonad m, VU.Unbox d)
  => Int -> Int -> (m (Int,Int,d)) -> m (MGraphData (PrimState m) d)
getUndirectedGraphMut !numVert !numEdges getEdge = do
  !degCount <- VUM.replicate (numVert+1) 0
  !connTable <- VUM.new (shiftL numEdges 1)
  write degCount connTable
  MGraphData connTable <$!> VU.unsafeFreeze degCount
  where
    write !degCount !connTable = do
      !temp <- do
        !temp <- VUM.new numEdges
        VU.forM_ (VU.generate numEdges id) $ \ !i -> do
          (!a,!b,!d) <- getEdge
          VUM.unsafeWrite temp i (a,b,d)
          VUM.modify degCount (+1) (a+1)
          VUM.modify degCount (+1) (b+1)
        VU.unsafeFreeze temp
      VU.foldM'
        (\ !total !i -> do
            !di <- VUM.unsafeRead degCount i
            VUM.unsafeWrite degCount i total
            return $! total+di)
        0 (VU.generate (numVert+1) id)
      VU.forM_ temp $ \(!a,!b,!d) -> do
        !ia <- VUM.read degCount (a+1)
        VUM.unsafeWrite degCount (a+1) $! ia+1
        VUM.unsafeWrite connTable ia $! (b,d)
        !ib <- VUM.read degCount (b+1)
        VUM.unsafeWrite degCount (b+1) $! ib+1
        VUM.unsafeWrite connTable ib $! (a,d)
      
getDirectedGraphMutForward :: (PrimMonad m, VU.Unbox d)
  => Int -> Int -> (m (Int,Int,d))
  -> m (MGraphData (PrimState m) d)
getDirectedGraphMutForward !numVert !numEdges getEdge = do
  !degCount <- VUM.replicate (numVert+1) 0
  !connTable <- VUM.new numEdges
  write degCount connTable
  MGraphData connTable <$!> VU.unsafeFreeze degCount
  where
    write !degCount !connTable = do
      !temp <- do
        !temp <- VUM.new numEdges
        VU.forM_ (VU.generate numEdges id) $ \ !i -> do
          (!a,!b,!d) <- getEdge
          VUM.unsafeWrite temp i (a,b,d)
          VUM.modify degCount (+1) (a+1)
        VU.unsafeFreeze temp
      VU.foldM'
        (\ !total !i -> do
            !di <- VUM.unsafeRead degCount i
            VUM.unsafeWrite degCount i total
            return $! total+di)
        0 (VU.generate (numVert+1) id)
      VU.forM_ temp $ \(!a,!b,!d) -> do
        !ia <- VUM.read degCount (a+1)
        VUM.unsafeWrite degCount (a+1) $! ia+1
        VUM.unsafeWrite connTable ia $! (b,d)

getDirectedGraphMutBidir :: (PrimMonad m, VU.Unbox d)
  => Int -> Int -> (m (Int,Int,d))
  -> m (MGraphData (PrimState m) d, MGraphData (PrimState m) d)
getDirectedGraphMutBidir !numVert !numEdges getEdge = do
  !fDegCount <- VUM.replicate (numVert+1) 0
  !fConnTable <- VUM.new numEdges
  !bDegCount <- VUM.replicate (numVert+1) 0
  !bConnTable <- VUM.new numEdges
  write fDegCount fConnTable bDegCount bConnTable
  !forward <- MGraphData fConnTable <$> VU.unsafeFreeze fDegCount
  !backward <- MGraphData bConnTable <$> VU.unsafeFreeze bDegCount
  return $! (forward,backward)
  where
    write !fDegCount !fConnTable !bDegCount !bConnTable = do
      !temp <- do
        !temp <- VUM.new numEdges
        VU.forM_ (VU.generate numEdges id) $ \ !i -> do
          (!a,!b,!d) <- getEdge
          VUM.unsafeWrite temp i (a,b,d)
          VUM.modify fDegCount (+1) (a+1)
          VUM.modify bDegCount (+1) (b+1)
        VU.unsafeFreeze temp
      VU.foldM'
        (\ !total !i -> do
            !di <- VUM.unsafeRead fDegCount i
            VUM.unsafeWrite fDegCount i total
            return $! total+di)
        0 (VU.generate (numVert+1) id)
      VU.foldM'
        (\ !total !i -> do
            !di <- VUM.unsafeRead bDegCount i
            VUM.unsafeWrite bDegCount i total
            return $! total+di)
        0 (VU.generate (numVert+1) id)
      VU.forM_ temp $ \(!a,!b,!d) -> do
        !ia <- VUM.read fDegCount (a+1)
        VUM.unsafeWrite fDegCount (a+1) $! ia+1
        VUM.unsafeWrite fConnTable ia $! (b,d)
        !ib <- VUM.read bDegCount (b+1)
        VUM.unsafeWrite bDegCount (b+1) $! ib+1
        VUM.unsafeWrite bConnTable ib $! (a,d)

#define IL(f) {-# INLINE f #-}; f

IL(evalVals) :: [a] -> [a]
evalVals xs = build $ \c n -> foldr (c $!) n xs
IL(forceVals) :: (NFData a) => [a] -> [a]
forceVals xs = build $ \c n -> foldr (c $!!) n xs

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

unlessM, whenM :: (Monad m) => m Bool -> m () -> m ()
IL(whenM) = (. flip when) . (>>=)
IL(unlessM) = (. flip unless) . (>>=)

IL(wrA) = A.writeArray
IL(rdA) = A.readArray
IL(mdA) = \arr f !i -> do
  ai <- rdA arr i
  let fai = f ai 
  wrA arr i fai
  return (ai,fai)
{-# INLINE mdA' #-}
mdA' = \arr f !i -> do
  !ai <- rdA arr i
  let !fai = f ai
  wrA arr i fai
  return (ai,fai)
IL(swapA) = \arr !i !j -> do
  ai <- rdA arr i
  wrA arr i =<< rdA arr j
  wrA arr j ai

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

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

#undef IL