Problem:
Score : 600 points

Problem Statement

Given is a directed graph G with N vertices and M edges.

The vertices are numbered 1 to N, and the i-th edge is directed from Vertex A_i to Vertex B_i.

It is guaranteed that the graph contains no self-loops or multiple edges.

Determine whether there exists an induced subgraph (see Notes) of G such that the in-degree and out-degree of every vertex are both 1. If the answer is yes, show one such subgraph.

Here the null graph is not considered as a subgraph.

Notes

For a directed graph G = (V, E), we call a directed graph G' = (V', E') satisfying the following conditions an induced subgraph of G:

V' is a (non-empty) subset of V.

E' is the set of all the edges in E that have both endpoints in V'.

Constraints

1 \leq N \leq 1000

0 \leq M \leq 2000

1 \leq A_i,B_i \leq N

A_i \neq B_i

All pairs (A_i, B_i) are distinct.

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
A_2 B_2
:
A_M B_M

Output

If there is no induced subgraph of G that satisfies the condition, print -1.
Otherwise, print an induced subgraph of G that satisfies the condition, in the following format:

K
v_1
v_2
:
v_K

This represents the induced subgraph of G with K vertices whose vertex set is \{v_1, v_2, \ldots, v_K\}. (The order of v_1, v_2, \ldots, v_K does not matter.)
If there are multiple subgraphs of G that satisfy the condition, printing any of them is accepted.

Sample Input 1

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

Sample Output 1

3
1
2
4

The induced subgraph of G whose vertex set is \{1, 2, 4\} has the edge set \{(1, 2), (2, 4), (4, 1)\}. The in-degree and out-degree of every vertex in this graph are both 1.

Sample Input 2

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

Sample Output 2

-1

There is no induced subgraph of G that satisfies the condition.

Sample Input 3

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

Sample Output 3

4
2
3
4
5

Solution in Haskell (GHC 7.10.3) (judge verdict: Runtime Error)

{-# LANGUAGE
  ScopedTypeVariables, BangPatterns, TupleSections, ExplicitForAll,
  LambdaCase, MultiWayIf, Unsafe, RecordWildCards, FlexibleContexts, CPP,
  NoMonomorphismRestriction, GADTs, PatternGuards, MagicHash, UnboxedTuples,
  RankNTypes, EmptyDataDecls, EmptyCase, ViewPatterns, PolyKinds,
  TypeFamilies, OverloadedStrings, FlexibleInstances, UndecidableInstances,
  DefaultSignatures, GeneralizedNewtypeDeriving, StandaloneDeriving,
  DeriveGeneric, DeriveFunctor, DeriveDataTypeable, DeriveFoldable,
  DeriveTraversable, DeriveDataTypeable #-}
{-# 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 Data.Data
import Data.Typeable
import GHC.Generics
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#)
import Control.Monad.Trans.Maybe
rIntS1 = subtract 1 <$> rIntS 

main :: IO ()
main = do
  [n,m] <- map readInt . words <$> getLine
  grph <- getDirectedGraphForward n m
    $ fromJust . evalStateT (liftA3 (,,) rIntS1 rIntS1 (return ()))
       <$> BS.getLine
  visited <- VUM.replicate n (0::Int)
  next <- VUM.replicate n (-1)
  let dfs :: Int -> IO Bool
      dfs !v = do
        visitedV <- VUM.read visited v
        case visitedV of
          2 -> return False
          1 -> return True
          0 -> do
            VUM.unsafeWrite visited v 1
            VU.foldr (\ (!v1,_) cont -> do
                         VUM.unsafeWrite next v v1
                         res <- dfs v1
                         if res then return True else cont)
              (do VUM.unsafeWrite visited v 2
                  VUM.unsafeWrite next v (-1)
                  return False)
              (edgesOut grph v)
  res <- foldr (\ !v cont -> do
                   res <- dfs v
                   if res then return True else cont) (return False) [0..n-1]
  if not res then print (-1) else do
  !v0 <- fromJust . VU.findIndex (>=0) <$> VU.unsafeFreeze next
  VUM.set visited 0
  let go :: Int -> IO ()
      go !v0 = do
        visit <- VUM.read visited v0
        unless (visit > 0) $ do
        VUM.unsafeWrite visited v0 1
        VU.forM_ (edgesOut grph v0) $ \ !(v1,_) -> do
          !next1 <- VUM.unsafeRead next v1
          when (next1 >= 0) $ do
            !next0 <- VUM.unsafeRead next v0
            VUM.unsafeWrite next v0 v1
            let go2 !next0
                  | next0 == v1 = return ()
                  | otherwise = do
                      !nextnext0 <- VUM.unsafeRead next next0
                      VUM.unsafeWrite next next0 (-1)
                      go2 nextnext0
            go2 next0
        VUM.unsafeRead next v0 >>= go
  go v0
  next_ <- VU.unsafeFreeze next
  let result = VU.map ((+1).fst)
        $ VU.filter ((>=0) . snd) $ VU.indexed next_
  print $ VU.length result
  printVecInLines $ result
  

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)




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

{-# 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 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

      
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)

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

class ShowAsBuilder a where
  showAsBuilder :: a -> BSB.Builder
  default showAsBuilder :: (Show a) => a -> BSB.Builder
  showAsBuilder = BSB.string8 . show

#define INS(t,f) instance ShowAsBuilder t where \
  { {-# INLINE showAsBuilder #-}; showAsBuilder=f }
INS(Int,BSB.intDec)
INS(Int8,BSB.int8Dec)
INS(Int16,BSB.int16Dec)
INS(Int32,BSB.int32Dec)
INS(Int64,BSB.int64Dec)
INS(Word,BSB.wordDec)
INS(Word8,BSB.word8Dec)
INS(Word16,BSB.word16Dec)
INS(Word32,BSB.word32Dec)
INS(Word64,BSB.word64Dec)
INS(Integer,BSB.integerDec)
INS(Float,BSB.floatDec)
INS(Double,BSB.doubleDec)
-- INS(String,BSB.string8) -- Inconsistent with Show
-- INS(BS.ByteString,BSB.byteString) -- Inconsistent with Show
-- INS(BSL.ByteString,BSB.lazyByteString) -- Inconsisitent with Show
#undef INS

-- Inconsistent with show
instance (ShowAsBuilder a, VG.Vector v a) => ShowAsBuilder (v a) where
  showAsBuilder = v2BSpcSep

{-# INLINE putBuilder #-}
putBuilder = BSB.hPutBuilder stdout

printVecInLines, printVecInSpcSepLn ::
  (VG.Vector v a, ShowAsBuilder a) => v a -> IO ()
{-# INLINE printVecInLines #-}
printVecInLines = putBuilder . v2BLines
{-# INLINE printVecInSpcSepLn #-}
printVecInSpcSepLn = putBuilder . v2BSpcSepLn

v2BSpcSepLn, v2BSpcSep, v2BConcat, v2BLines ::
  (VG.Vector v a, ShowAsBuilder a)
  => v a -> BSB.Builder
{-# INLINE v2BSpcSepLn #-}
v2BSpcSepLn = v2BSpcSepLnWith showAsBuilder
{-# INLINE v2BSpcSep #-}
v2BSpcSep = v2BSpcSepWith showAsBuilder
{-# INLINE v2BConcat #-}
v2BConcat = v2BConcatWith showAsBuilder
{-# INLINE v2BLines #-}
v2BLines = v2BLinesWith showAsBuilder


v2BSpcSepLnWith, v2BSpcSepWith, v2BConcatWith, v2BLinesWith ::
  (VG.Vector v a)
  => (a -> BSB.Builder) -- ^ show function
  -> v a -> BSB.Builder
{-# INLINE v2BSpcSepLnWith #-}
v2BSpcSepLnWith = v2BSpcSepPostfWith "\n"
{-# INLINE v2BSpcSepWith #-}
v2BSpcSepWith = v2BSpcSepPostfWith ""
{-# INLINE v2BConcatWith #-}
v2BConcatWith showFct = VG.foldr ((<>) . showFct) mempty
{-# INLINE v2BLinesWith #-}
v2BLinesWith showFct
  = VG.foldr (\ a -> (showFct a <>) . (BSB.char7 '\n' <>)) mempty


v2BSpcSepPostf :: (VG.Vector v a, ShowAsBuilder a)
  => BS.ByteString -- ^ postfix
  -> v a -> BSB.Builder
{-# INLINE v2BSpcSepPostf #-}
v2BSpcSepPostf = (`v2BSpcSepPostfWith` showAsBuilder)

v2BSpcSepPostfWith :: (VG.Vector v a)
  => BS.ByteString -- ^ postfix
  -> (a -> BSB.Builder) -- ^ show function
  -> v a -> BSB.Builder
{-# INLINE v2BSpcSepPostfWith #-}
v2BSpcSepPostfWith = vecToBuilder "" " "

{-# INLINE vecToBuilder #-}
vecToBuilder :: (VG.Vector v a)
  => BS.ByteString -- ^ prefix
  -> BS.ByteString -- ^ separator
  -> BS.ByteString -- ^ postfix
  -> (a -> BSB.Builder) -- ^ show function
  -> v a -> BSB.Builder
vecToBuilder !prefix !separator !postfix
  = vecToBuilder_ (BSB.byteString prefix)
                  (BSB.byteString separator)
                  (BSB.byteString postfix)


{-# INLINE vecToBuilder_ #-}
vecToBuilder_ :: (VG.Vector v a)
  => BSB.Builder -- ^ prefix
  -> BSB.Builder -- ^ separator
  -> BSB.Builder -- ^ postfix
  -> (a -> BSB.Builder) -- ^ show function
  -> v a -> BSB.Builder
vecToBuilder_ !prefix !separator !postfix showFct vec
  = prefix <> VG.foldr
    (\ a rest !prefx -> prefx <> (showFct a <> rest separator))
    (const postfix) vec mempty

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

getVecGLn :: (VG.Vector v a) =>
           Int -> StateT BS.ByteString Maybe a -> IO (v a)
getVecGLn n s = VG.unfoldrN n (runStateT s) <$> BS.getLine
{-# INLINE getVecGLn #-}
getVecGRest :: (VG.Vector v a) =>
            Int -> StateT BSL.ByteString Maybe a -> IO (v a)
getVecGRest n s = VG.unfoldrN n (runStateT s) <$> BSL.getContents
{-# INLINE getVecGRest #-}
getVecLn :: Int -> StateT BS.ByteString Maybe a -> IO (V.Vector a)
getVecLn = getVecGLn
{-# INLINE getVecLn #-}
getVecRest :: Int -> StateT BSL.ByteString Maybe a -> IO (V.Vector a)
getVecRest = getVecGRest
{-# INLINE getVecRest #-}
getVecULn :: (VU.Unbox a) =>
  Int -> StateT BS.ByteString Maybe a -> IO (VU.Vector a)
getVecULn = getVecGLn
{-# INLINE getVecULn #-}
getVecURest :: (VU.Unbox a) =>
  Int -> StateT BSL.ByteString Maybe a -> IO (VU.Vector a)
getVecURest = getVecGRest
{-# INLINE getVecURest #-}

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