Problem:
Score : 600 points

Problem Statement

We have a tree with N vertices numbered 1 to N. The i-th edge in this tree connects Vertex a_i and b_i.
For each k=1, ..., N, solve the problem below:

Consider writing a number on each vertex in the tree in the following manner:

First, write 1 on Vertex k.

Then, for each of the numbers 2, ..., N in this order, write the number on the vertex chosen as follows:

Choose a vertex that still does not have a number written on it and is adjacent to a vertex with a number already written on it. If there are multiple such vertices, choose one of them at random.

Find the number of ways in which we can write the numbers on the vertices, modulo (10^9+7).

Constraints

2 \leq N \leq 2 \times 10^5

1 \leq a_i,b_i \leq N

The given graph is a tree.

Input

Input is given from Standard Input in the following format:

N
a_1 b_1
:
a_{N-1} b_{N-1}

Output

For each k=1, 2, ..., N in this order, print a line containing the answer to the problem.

Sample Input 1

3
1 2
1 3

Sample Output 1

2
1
1

The graph in this input is as follows:

For k=1, there are two ways in which we can write the numbers on the vertices, as follows:

Writing 1, 2, 3 on Vertex 1, 2, 3, respectively

Writing 1, 3, 2 on Vertex 1, 2, 3, respectively

Sample Input 2

2
1 2

Sample Output 2

1
1

The graph in this input is as follows:

Sample Input 3

5
1 2
2 3
3 4
3 5

Sample Output 3

2
8
12
3
3

The graph in this input is as follows:

Sample Input 4

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

Sample Output 4

40
280
840
120
120
504
72
72

The graph in this input is as follows:

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, OverloadedStrings, FlexibleInstances, UndecidableInstances,
  DefaultSignatures, GeneralizedNewtypeDeriving, StandaloneDeriving,
  DeriveGeneric, DeriveFunctor, DeriveDataTypeable, DeriveFoldable,
  DeriveTraversable, DeriveDataTypeable, FlexibleInstances,
  MultiParamTypeClasses #-}
{-# OPTIONS_GHC -O2 #-}

#define PHASE_FUSED [1]
#define PHASE_INNER [0]
#define INLINE_FUSED INLINE PHASE_FUSED
#define INLINE_INNER INLINE PHASE_INNER

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.Functor.Identity
import Data.Data
import Data.Typeable
import GHC.Generics
import System.IO
import System.IO.Unsafe (unsafeDupablePerformIO, unsafePerformIO)
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 as BSW
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy as BSLW
import qualified Data.ByteString.Lazy.Char8 as BSL
import qualified Data.ByteString.Builder as BSB
import qualified Data.ByteString.Unsafe as BSU
import qualified Data.ByteString.Internal as BSU
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.Vector.Fusion.Bundle.Monadic as VFBM
import qualified Data.Vector.Fusion.Bundle as VFB
import qualified Data.Vector.Fusion.Stream.Monadic as VFSM
import qualified Data.Vector.Fusion.Bundle.Size as VFBS
import qualified Data.Vector.Fusion.Util as VFU
import qualified Data.Attoparsec.ByteString.Char8 as Atto
import Debug.Trace
import Unsafe.Coerce
import Foreign.ForeignPtr
import GHC.Exts (build, Int(..), Int#,
                 (+#), (*#), (-#), (<#), (>=#), (==#), quotRemInt#,
                 remInt#, uncheckedIShiftRL#, andI#, orI#,
                isTrue#, Addr#, Ptr(..))
rInt1 = subtract 1 <$> rIntS

main :: IO ()
main = do
  n <- readInt <$> getLine
  grph@(GraphData edges_ cuts) <- getUndirectedGraph n (n-1)
    $ readLnWith $ liftA2 (,,()) rInt1 rInt1
  dp <- VUM.replicate n (-1::Int,remF 0) 
  let edges = fst $ VU.unzip edges_
      goDown :: Int -> Int -> (Int,RemF)
      goDown !parent !this = BSU.accursedUnutterablePerformIO $ do
        !res@(!nodes,!_) <- VUM.unsafeRead dp this
        if nodes >= 0 then return res else do
          let !res@(!_,!_) = goCalc parent this
          VUM.unsafeWrite dp this res
          return res
      goCalc :: Int -> Int -> (Int,RemF)
      goCalc !parent !this = (resNodes,resWays)
        where
          !resNodes = nodesCh + 1
          !resWays = multInv * facto nodesCh
          !beg = cuts VU.! this
          !end = cuts VU.! (this+1)
          !(!nodesCh, !multInv)
            = VU.foldl' (\(!accNodes, !accMult) (!nodes,!ways) ->
                           let !accNodes1 = accNodes + nodes
                               !accMult1 = accMult * ways * factoInv nodes
                           in (accNodes1, accMult1))
              (0,remF 1)
              $ VU.map (\ !child -> goDown this child)
              $ VU.filter (/=parent)
              $ VU.unsafeBackpermute edges
              $ VU.generate (end-beg) (+beg)
  dp2 <- VUM.replicate n (-1::Int,remF 0)
  let !_ = goDown (-1) 0
      goUp :: Int -> Int -> Int -> RemF -> IO ()
      goUp !parent !this !cntUp !waysUp = do
        VUM.write dp2 this (cntUp,waysUp)
        let !(!nodes,!invMult) =
              VU.foldl' (\ (!n,!im) (!n2,!im2) -> (n+n2,im*im2))
                 (cntUp,factoInv cntUp * waysUp)
              $ VU.map (\(!nodes, !mult) -> (nodes,factoInv nodes * mult))
              $ VU.map (\ !child -> goDown this child)
              $ VU.filter (/= parent)
              $ VU.unsafeBackpermute edges
              $ VU.generate (end-beg) (+beg)
        VU.forM_ (VU.filter (/=parent) $ VU.unsafeBackpermute edges
                   $ VU.generate (end-beg) (+beg)) $ \ !child -> do
          let (!nodes, !mult) = goDown this child
          goUp this child (n - nodes)
            $! facto (n-nodes-1) * invMult / (factoInv nodes * mult) 
          where 
            !beg = cuts VU.! this
            !end = cuts VU.! (this+1)
  goUp (-1) 0 0 $ remF 1
  downs <- VU.unsafeFreeze dp
  ups <- VU.unsafeFreeze dp2
  let res = VU.zipWith (\(nodesCh,dn) (nodesUp,up) -> dn*up*comb (n-1) nodesUp)
            downs ups
  printVecInLines $ unVRem res
  return ()
      

theModulus :: Word32
theModulus = 1000000007

comb :: Int -> Int -> RemF
comb n k | n < 0 || k < 0 || k > n = 0
         | otherwise = facto n * factoInv (n-k) * factoInv k


factos :: VU.Vector RemF
factos = VU.scanl' (*) 1 $ VU.map Rem $ VU.tail
         $ VU.generate 200001 fromIntegral
factoInvs :: VU.Vector RemF
factoInvs = VU.reverse $ VU.scanl' (*) (recip $ VU.last factos) $
  VU.map (Rem . fromIntegral) $ VU.generate 200000 (200000-)

facto :: Int -> RemF
{-# INLINE facto #-}
facto = (factos VU.!)
factoInv :: Int -> RemF
{-# INLINE factoInv #-}
factoInv = (factoInvs VU.!)

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)


data FixedModulus

instance HasWord32 FixedModulus where
  {-# INLINE CONLIKE word32Val #-}
  word32Val = const 1000000007 -- 10^9 + 7

type RemF = Rem FixedModulus

pxyF :: Proxy FixedModulus
pxyF = Proxy
remF :: Word32 -> RemF
{-# INLINE CONLIKE remF #-}
remF = Rem

newtype Magic r = Magic (forall (m :: *). HasWord32 m => Proxy m -> r)

{-# INLINE reifyWord32 #-}
reifyWord32 :: forall a. Word32 ->
  (forall (m :: *). HasWord32 m => Proxy m -> a) -> a
reifyWord32 v f = unsafeCoerce (Magic f :: Magic a) (const v) Proxy

newtype Rem m = Rem {unRem :: Word32} deriving (Eq)

withTypeArgOf :: c a -> d a -> c a
{-# INLINE CONLIKE withTypeArgOf #-}
withTypeArgOf = const

proxyFor :: c a -> Proxy a
{-# INLINE CONLIKE proxyFor #-}
proxyFor = const Proxy

withProxy :: (Proxy m -> c m) -> c m
{-# INLINE withProxy #-}
withProxy f = f Proxy

remP :: Proxy m -> Word32 -> Rem m
{-# INLINE CONLIKE remP #-}
remP = const Rem

{-# INLINE modulus32 #-}
modulus32 :: HasWord32 m => Rem m -> Word32
modulus32 x = word32Val $ proxyFor x

class HasWord32 m where
  word32Val :: Proxy m -> Word32

instance Show (Rem m) where
  {-# INLINE showsPrec #-}
  showsPrec = coerce `asTypeOf` (\f p (Rem v) -> f p v) $ showsPrec

negRem :: HasWord32 m => Rem m -> Rem m
{-# INLINE negRem #-}
negRem x0@(Rem x)
  | x == 0 = Rem 0
  | otherwise = Rem $ modulus32 x0 - x

addRem, subRem, multRem
  :: HasWord32 m => Rem m -> Rem m -> Rem m
{-# INLINE subRem #-}
subRem x0@(Rem x) (Rem y) = Rem $ x-y + if x < y then modulus32 x0 else 0
{-# INLINE addRem #-}
addRem x0@(Rem x) (Rem y) = Rem $ x-negy + if x < negy then m else 0
  where m = modulus32 x0; negy = m-y
{-# INLINE multRem #-}
multRem x0@(Rem x) (Rem y)
  = Rem $ toW32 $ (toW64 x * toW64 y) `rem` toW64 (modulus32 x0)

{-# INLINE fromIntegerRem #-}
fromIntegerRem :: (HasWord32 m) => Integer -> Rem m
fromIntegerRem x = withProxy $ Rem . fromInteger . mod x . toInteger . word32Val

{-# INLINE signumRem #-}
signumRem :: (HasWord32 m) => Rem m -> Rem m
signumRem = (\case True -> Rem 0; False -> Rem 1) . (== Rem 0)

instance HasWord32 m => Num (Rem m) where
  {-# INLINE negate #-}
  negate = negRem
  {-# INLINE (-) #-}
  (-) = subRem
  {-# INLINE (+) #-}
  (+) = addRem
  {-# INLINE (*) #-}
  (*) = multRem
  {-# INLINE fromInteger #-}
  fromInteger = fromIntegerRem
  {-# INLINE abs #-}
  abs = id
  {-# INLINE signum #-}
  signum = signumRem

recipRem :: HasWord32 m => Rem m -> Rem m
{-# INLINE recipRem #-}
recipRem = \x -> x ^ (modulus32 x - 2)

-- works only for primes
instance HasWord32 m => Fractional (Rem m) where
  {-# INLINE recip #-}
  recip = recipRem
  fromRational q = fromInteger (numerator q) / fromInteger (denominator q)

newtype instance VU.Vector (Rem m)
  = VRem { unVRem :: VU.Vector Word32 }
newtype instance VUM.MVector s (Rem m)
  = VMRem { unVMRem :: VUM.MVector s Word32 }
instance VUM.Unbox (Rem m)

instance VGM.MVector VUM.MVector (Rem m) where
  {-# INLINE basicLength #-}
  basicLength = coerce `asTypeOf` (. unVMRem) $ VGM.basicLength
  {-# INLINE basicUnsafeSlice #-}
  basicUnsafeSlice
    = coerce `asTypeOf` (\f x y (VMRem v) -> VMRem $ f x y v)
      $ VGM.basicUnsafeSlice
  {-# INLINE basicOverlaps #-}
  basicOverlaps = coerce `asTypeOf` (`on` unVMRem) $ VGM.basicOverlaps
  {-# INLINE basicUnsafeNew #-}
  basicUnsafeNew = fmap (coerce `asTypeOf` VMRem) . VGM.basicUnsafeNew
  {-# INLINE basicInitialize #-}
  basicInitialize = coerce `asTypeOf` (. unVMRem) $ VGM.basicInitialize
  {-# INLINE basicUnsafeReplicate #-}
  basicUnsafeReplicate !n
    = fmap (coerce `asTypeOf` VMRem) . VGM.basicUnsafeReplicate n
    . unRem
  {-# INLINE basicUnsafeRead #-}
  basicUnsafeRead (VMRem v) i = coerce `asTypeOf` Rem <$>
                                VGM.basicUnsafeRead v i
  {-# INLINE basicUnsafeWrite #-}
  basicUnsafeWrite = coerce `asTypeOf` (\f (VMRem v) n (Rem x) -> f v n x)
                     $ VGM.basicUnsafeWrite
  {-# INLINE basicClear #-}
  basicClear = coerce `asTypeOf` (. unVMRem) $ VGM.basicClear
  {-# INLINE basicSet #-}
  basicSet = coerce `asTypeOf` (\f (VMRem v) (Rem x) -> f v x) $ VGM.basicSet
  {-# INLINE basicUnsafeCopy #-}
  basicUnsafeCopy = coerce `asTypeOf` (`on` unVMRem) $ VGM.basicUnsafeCopy
  {-# INLINE basicUnsafeMove #-}
  basicUnsafeMove = coerce `asTypeOf` (`on` unVMRem) $ VGM.basicUnsafeMove
  {-# INLINE basicUnsafeGrow #-}
  basicUnsafeGrow (VMRem v) !n
    = fmap (coerce `asTypeOf` VMRem) $ VGM.basicUnsafeGrow v n

instance VG.Vector VU.Vector (Rem m) where
  {-# INLINE basicUnsafeFreeze #-}
  basicUnsafeFreeze (VMRem v)
    = (coerce `asTypeOf` VRem) <$> VG.basicUnsafeFreeze v
  {-# INLINE basicUnsafeThaw #-}
  basicUnsafeThaw (VRem v)
    = (coerce `asTypeOf` VMRem) <$> VG.basicUnsafeThaw v
  {-# INLINE basicLength #-}
  basicLength = coerce `asTypeOf` (. unVRem) $ VG.basicLength
  {-# INLINE basicUnsafeSlice #-}
  basicUnsafeSlice
    = coerce `asTypeOf` (\f i l (VRem v) -> VRem $ f i l v)
      $ VG.basicUnsafeSlice
  {-# INLINE basicUnsafeIndexM #-}
  basicUnsafeIndexM (VRem !v) !i = coerce <$> VG.basicUnsafeIndexM v i
  {-# INLINE basicUnsafeCopy #-}
  basicUnsafeCopy
    = coerce `asTypeOf` (\f (VMRem mv) (VRem v) -> f mv v)
      $ VG.basicUnsafeCopy
  {-# INLINE elemseq #-}
  elemseq = const seq



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(putBuilder) = BSB.hPutBuilder stdout

printVecInLines, printVecInSpcSepLn ::
  (VG.Vector v a, ShowAsBuilder a) => v a -> IO ()
IL(printVecInLines) = putBuilder . v2BLines
IL(printVecInSpcSepLn) = putBuilder . v2BSpcSepLn

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

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

#define INS(t,f) instance ShowAsBuilder t where { IL(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, ShowAsBuilder b) => ShowAsBuilder (a,b) where
  IL(showAsBuilder) = showTupAsBuilder
instance (ShowAsBuilder a, ShowAsBuilder b, ShowAsBuilder c) =>
  ShowAsBuilder (a,b,c) where
  IL(showAsBuilder) = showTup3AsBuilder
instance (ShowAsBuilder a, ShowAsBuilder b, ShowAsBuilder c, ShowAsBuilder d) =>
  ShowAsBuilder (a,b,c,d) where
  IL(showAsBuilder) = showTup4AsBuilder

IL(showTupAsBuilderWith)
  :: (a -> BSB.Builder) -> (b -> BSB.Builder) -> (a,b) -> BSB.Builder
showTupAsBuilderWith showA showB
  = \(a,b) -> (showA a <>) $ BSB.char7 ' ' <> showB b
IL(showTupAsBuilder) :: (ShowAsBuilder a, ShowAsBuilder b)
  => (a,b) -> BSB.Builder
showTupAsBuilder = showTupAsBuilderWith showAsBuilder showAsBuilder 

IL(showTup3AsBuilderWith) :: (a -> BSB.Builder) -> (b -> BSB.Builder) ->
  (c -> BSB.Builder) -> (a,b,c) -> BSB.Builder
showTup3AsBuilderWith showA showB showC
  = \(a,b,c) -> (showA a <>) $ (BSB.char7 ' ' <>) $ (showB b <>)
                $ (BSB.char7 ' ' <>) $ showC c
IL(showTup3AsBuilder) :: (ShowAsBuilder a, ShowAsBuilder b, ShowAsBuilder c)
  => (a,b,c) -> BSB.Builder
showTup3AsBuilder
  = showTup3AsBuilderWith showAsBuilder showAsBuilder showAsBuilder

IL(showTup4AsBuilderWith) :: (a -> BSB.Builder) -> (b -> BSB.Builder) ->
  (c -> BSB.Builder) -> (d -> BSB.Builder) -> (a,b,c,d) -> BSB.Builder
showTup4AsBuilderWith showA showB showC showD
  = \(a,b,c,d) -> (showA a <>) $ (BSB.char7 ' ' <>)
                  $ showTup3AsBuilderWith showB showC showD (b,c,d)
IL(showTup4AsBuilder) ::
  (ShowAsBuilder a, ShowAsBuilder b, ShowAsBuilder c, ShowAsBuilder d) =>
  (a,b,c,d) -> BSB.Builder
showTup4AsBuilder = showTup4AsBuilderWith showAsBuilder showAsBuilder
                    showAsBuilder showAsBuilder

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


v2BSpcSepLnWith, v2BSpcSepWith, v2BConcatWith, v2BLinesWith ::
  (VG.Vector v a)
  => (a -> BSB.Builder) -- ^ show function
  -> v a -> BSB.Builder
IL(v2BSpcSepLnWith) = v2BSpcSepPostfWith $ BS.singleton '\n'
IL(v2BSpcSepWith) = v2BSpcSepPostfWith BS.empty
IL(v2BConcatWith) showFct = VG.foldr ((<>) . showFct) mempty
IL(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
IL(v2BSpcSepPostf) = (`v2BSpcSepPostfWith` showAsBuilder)

v2BSpcSepPostfWith :: (VG.Vector v a)
  => BS.ByteString -- ^ postfix
  -> (a -> BSB.Builder) -- ^ show function
  -> v a -> BSB.Builder
IL(v2BSpcSepPostfWith) = vecToBuilder BS.empty $ BS.singleton ' '

IL(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)


IL(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

IL(readLnWith) :: StateT BS.ByteString Maybe a -> IO a
readLnWith parser = fromJust . evalStateT parser <$> BS.getLine
IL(readContentWith) :: StateT BSL.ByteString Maybe a -> IO a
readContentWith parser = fromJust . evalStateT parser <$> BSL.getContents

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

IL(rIntL) :: StateT BSL.ByteString Maybe Int
rIntL = skipSpecialL $ StateT BSL.readInt
IL(rIntS) :: StateT BS.ByteString Maybe Int
rIntS = skipSpecialS $ StateT BS.readInt
IL(rStrL) :: (MonadState BSL.ByteString m) => m BS.ByteString
rStrL = skipSpecialL $ BSL.toStrict <$> state (BSL.span (>='!'))
IL(rStrS) :: (MonadState BS.ByteString m) => m BS.ByteString
rStrS = skipSpecialS $ state $ BS.span (>='!')
IL(rCharL) :: StateT BSL.ByteString Maybe Char
rCharL = StateT BSL.uncons
IL(rCharS) :: StateT BS.ByteString Maybe Char
rCharS = StateT BS.uncons
IL(dropSpecialL) :: (MonadState BSL.ByteString m) => m ()
dropSpecialL = modify $ BSL.dropWhile (<'!')
IL(dropSpecialS) :: (MonadState BS.ByteString m) => m ()
dropSpecialS = modify $ BS.dropWhile (<'!')
IL(skipSpecialL) :: (MonadState BSL.ByteString m) => m a -> m a
skipSpecialL = (dropSpecialL *>)
IL(skipSpecialS) :: (MonadState BS.ByteString m) => m a -> m a
skipSpecialS = (dropSpecialS *>)

IL(linToMat) :: (VG.Vector v a) => Int -> Int -> v a -> V.Vector (v a)
linToMat h w lvec = vEvalElemsId $ V.generate h (\i -> VG.slice (i*w) w lvec)

IL(mLinToMat) :: (VGM.MVector v a) => Int -> Int -> v s a -> V.Vector (v s a)
mLinToMat h w lvec = vEvalElemsId $ V.generate h (\i -> VGM.slice (i*w) w lvec)
  
IL(unsafeAddrToSVec) :: Int -> Addr# -> VS.Vector Word8
unsafeAddrToSVec n addr
  = (`VS.unsafeFromForeignPtr0` n)
    $ unsafeDupablePerformIO
    $ newForeignPtr_ $ Ptr addr

IL(vEvalElemsId) :: (VG.Vector v a) => v a -> v a
vEvalElemsId = vMapFoldl (\ !_ !x -> (x,())) ()

IL(vEvalElems) :: (VG.Vector v a) => v a -> ()
vEvalElems = VG.foldl' (\ !_ !_ -> ()) () 

IL(vMapFoldl) :: (VG.Vector v b, VG.Vector v c) =>
  (a -> b -> (c,a)) -> a -> v b -> v c
vMapFoldl f a
  = VG.unstream . VFB.inplace (streamMapFoldl f a) id . VG.stream

streamMapFoldl :: (Functor m) =>
  (a -> b -> (c,a)) -> a -> VFSM.Stream m b -> VFSM.Stream m c
{-# INLINE_FUSED streamMapFoldl #-}
streamMapFoldl f a (VFSM.Stream step s) = VFSM.Stream step1 (a,s)
  where
    {-# INLINE_INNER step1 #-}
    step1 (a0,s0) =  (<$> step s0) $ \r -> case r of
      VFSM.Yield b s1 -> case f a0 b of (c,a1) -> VFSM.Yield c (a1,s1)
      VFSM.Skip    s1 -> VFSM.Skip (a0,s1)
      VFSM.Done       -> VFSM.Done

IL(svecToBS) :: VS.Vector Word8 -> BS.ByteString
svecToBS vec = BSU.fromForeignPtr ptr 0 len
  where (ptr, len) = VS.unsafeToForeignPtr0 vec


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 TS(f,a,m,init)\
  IL(f) :: forall e i s. (C(a,m) A.Ix i) => (i,i) -> init m (a i e); f
#define N(f,g,h,a,m)\
  TS(f,a,m,e->)=A.newArray;\
  TS(g,a,m,)=A.newArray_;\
  TS(h,a,m,[e]->)=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 TS

#undef IL