buildns cs lvs acc (n, accn) x = ((myn, myt), (x, myt) : acc')
    where
        accn' = (x, lvs ! x) : accn
        mcs = cs ! x
        f ((nn, t), acc) c = (if nn' < nn then (nn', t') else (nn, t), acc')
            where
                ((nn', t'), acc') = buildns cs lvs acc (succ n, accn') c
        (acc', myn, myt) =
            if null mcs
                then
                    let (_, t) = buildpt (succ n) accn'
                        in (acc, n, t)
                else
                    let (mmc : mmcs) = mcs
                        init = buildns cs lvs acc (succ n, accn') mmc
                        ((n', t'), acc') = foldl f init mmcs
                        in (acc', n', t')
buildns cs lvs acc (n, accn) x = ((myn, myt), (x, myt) : acc')
    where
        accn' = (x, lvs ! x) : accn
        mcs = cs ! x
        f ((nn, t), acc) c = (if nn' < nn then (nn', t') else (nn, t), acc')
            where
                ((nn', t'), acc') = buildns cs lvs acc (succ n, accn') c
        (acc', myn, myt) =
            if null mcs
                then
                    let (_, t) = buildpt (succ n) accn'
                        in (acc, n, t)
                else
                    let (mmc : mmcs) = mcs
                        init = buildns cs lvs acc (succ n, accn') mmc
                        ((n', t'), acc') = foldl f init mmcs
                        in (acc', n', t')
buildns cs lvs acc (n, accn) x = ((myn, myt), (x, myt) : acc')
    where
        accn' = (x, lvs ! x) : accn
        mcs = cs ! x
        f ((nn, t), acc) c = (if nn' < nn then (nn', t') else (nn, t), acc')
            where
                ((nn', t'), acc') = buildns cs lvs acc (succ n, accn') c
        (acc', myn, myt) =
            if null mcs
                then
                    let (_, t) = buildpt (succ n) accn'
                        in (acc, n, t)
                else
                    let (mmc : mmcs) = mcs
                        init = buildns cs lvs acc (succ n, accn') mmc
                        ((n', t'), acc') = foldl f init mmcs
                        in (acc', n', t')