Home > front end >  Contest problem: TIME_LIMIT_EXCEEDED for Haskell solution
Contest problem: TIME_LIMIT_EXCEEDED for Haskell solution

Time:08-15

I'm trying to solve this problem https://codeforces.com/contest/285/problem/C?locale=en. On test #7 I have got TIME_LIMIT_EXCEEDED (the limit is 1000ms). How can I optimize my solution?

import Data.List
import Data.Int

(|>) a b = b a

main = do
    s1 <- getLine
    s2 <- getLine
    let n = s1 |> (read :: String -> Int64)
        a = s2 |> words |> map (read :: String -> Int64)
        r = sort a |> zipWith (\x y -> abs (x - y)) [1 .. n] |> sum
    print r

Test output:

Test: #7, time: 1000 ms., memory: 98516 KB, exit code: -1, checker exit code: 0, verdict: TIME_LIMIT_EXCEEDED

Input
300000
299996 65 64 63 62 61 60 59 58 70 53 79 88 97 106 115 124 133 142 45 151 160 169 178 187 196 ...

CodePudding user response:

The solution was to switch to ByteString based I/O as suggested by Dogbert.

import Data.Maybe
import Data.List
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as C

-- NOTE: This will throw an error if parsing fails.
readInt :: B.ByteString -> Integer
readInt = fst . fromJust . C.readInteger

(|>) a b = b a

main = do
    s1 <- B.getLine
    s2 <- B.getLine
    let n = s1 |> readInt
        a = s2 |> C.words |> map readInt
        r = sort a |> zipWith (\x y -> abs (x - y)) [1 .. n] |> sum
    print r
  • Related