Sort by

recency

|

31 Discussions

|

  • + 0 comments

    scala:

    import scala.io.StdIn
    import scala.collection.Searching.{Found, InsertionPoint}
    
    object Solution {
      private def minSubset(acc: Seq[BigInt])(s: BigInt): Int = {
        acc.search(s) match {
          case Found(idx)          => idx
          case InsertionPoint(idx) => if (idx >= acc.length) -1 else idx
        }
      }
    
      def main(args: Array[String]): Unit = {
        val arr = Iterator
          .continually(StdIn.readLine())
          .takeWhile(null != _)
          .map(_.trim)
        arr.next().toInt
        val numbers = arr.next().split(" ").map(_.toInt).sorted(Ordering[Int].reverse).toIndexedSeq
        val sums = numbers.scanLeft(BigInt(0))(_ + _)
        val t = arr.next().toInt
        (1 to t)
          .map(_ => BigInt(arr.next()))
          .map(minSubset(sums))
          .foreach(println)
      }
    }
    
  • + 0 comments

    Irritating to get it done before timeouts, but satisfying to see it solved :-)

    haskell:

    module Main where
    
    import Data.List (sort, sortBy, span)
    import qualified Data.Map  as M
    
    type Query2Index = M.Map Int Int
    
    solve :: [Int] -> [Int] -> Query2Index
    solve _ [] = M.empty
    solve [] _ = M.empty
    solve xs qs = go mInitial iInitial totalInitial xsSorted qsSorted
      where
        mInitial = M.fromList $ [(q, -1) | q <- qs] -- (-1) is the fail value
        iInitial = 0
        totalInitial = 0
        xsSorted = sortBy (flip compare) xs -- DESC
        qsSorted = M.keys mInitial -- work of "sort qs" already done (ASC)
        {-
            Walk through the xs once, lobbing off qs from the front as we go
        -}
        go m _ _ [] _ = m -- ran out of xs
        go m _ _ _ [] = m -- ran out of qs
        go m accI accT xs' qs' =
            let
                newTotal = accT + head xs' -- running total of dec sorted xs
                newIndex = accI + 1 -- index is size of subset
                (covered, remaining) = span (<= newTotal) qs'
                -- Map.union is left-biased, so we can just add to the existing map
                m' = M.union (M.fromList [(q, newIndex) | q <- covered]) m
             in
                go m' newIndex newTotal (tail xs') remaining
    
    main :: IO ()
    main = do
        sizeLine <- getLine -- not used
        dataLine <- getLine
        let xs = map read $ words dataLine :: [Int]
    
        queryLine <- getLine -- not used
        queryLines <- getContents
        let qs = map read $ lines queryLines :: [Int]
    
        -- return a map of queries to their indecies (or -1 if not covered)
        let m = solve xs qs
    
        -- required display format, in the original order of the queries
        let result = map (m M.!) qs
        mapM_ print result
    
  • + 0 comments

    Simple O(n lg n) solution in Haskell using Data.Set:

    import Control.Monad (replicateM_)
    import Data.Int
    import Data.Set hiding (foldl)
    import Data.List (sort)
    
    main :: IO ()
    main = getLine >> do
      l' <- getLine
      let l = preprocess $ fmap read $ words l'
      readLn >>= flip replicateM_
        (readLn >>= print . maybe (- 1) (flip findIndex l) . flip lookupGE l)
    
    preprocess :: [Int64] -> Set Int64
    preprocess = fromList . scanl (+) 0 . reverse . sort
    
  • + 0 comments

    f# solution

    open System
    
    let binarySearchMin predicate (arr: int64[]) =
        let rec loop a b lastFound =
            match a, b with
            | a, b when a = b && lastFound > 0 -> lastFound
            | a, b when a = b -> -1
            | _ ->
                let mid = (b - a + 1) / 2
                let checkAt = a + mid
    
                match predicate arr.[checkAt] with
                | false -> loop (a + mid) b lastFound
                | true -> loop a (b - mid) checkAt
    
        loop 0 ((Array.length arr) - 1) (-1)
    
    let search s arr = (binarySearchMin (fun x -> x >= s) arr)
    
    let N = Console.ReadLine() |> int
    
    let arr =
        Console.ReadLine()
        |> (fun s -> s.Split(" "))
        |> Array.map int
        |> Array.sortDescending
        |> Array.scan (fun acc curr -> acc + (int64 curr)) 0L
    
    let t = Console.ReadLine() |> int
    
    [ 1..t ]
    |> Seq.map (fun _ -> Console.ReadLine() |> int64)
    |> Seq.map (fun s -> search s arr)
    |> Seq.map string
    |> Seq.iter Console.WriteLine
    
  • + 0 comments

    haskell

    import Data.List (sortOn, intercalate)
    import Data.Ord (Down(Down))
    import Data.Array (listArray, bounds, (!))
    
    fromList xs = listArray (1, length xs) xs
    
    -- arr is non-decreasing
    help arr low (beg, end)
      | beg == end = beg
      | val >= low = help arr low (beg, med)
      | otherwise = help arr low (med+1, end)
      where med = (beg + end) `div` 2
            val = arr ! med
    
    search arr low
      | low <= arr ! beg = Just beg
      | low > arr ! end = Nothing
      | otherwise = Just $ help arr low (beg, end)
      where bnds = bounds arr
            beg = fst bnds
            end = snd bnds
    
    ans Nothing = -1
    ans (Just x) = x
    
    main = do
      ls <- fmap lines getContents
      let as = map read $ words $ ls !! 1 :: [Int]
          ss = map read $ drop 3 ls :: [Int]
          arr = fromList $ scanl1 (+) $ sortOn Down as
      putStrLn $ intercalate "\n" $ map (show . ans . search arr) ss