Domanda

Hmmm ... la sua un pò difficile trovare un metodo per la lettura / scrittura dei dati abbastanza veloce per avere accettato a questo problema ( https://www.spoj.pl/problems/INTEST/ ) utilizzando F # .

Il mio codice ( http://paste.ubuntu.com/548748/ ) ottiene TLE. ..

Tutte le idee su come velocizzare la lettura dei dati?

È stato utile?

Soluzione

Questa versione mio passa il tempo limite (ma è ancora terribilmente lento ~ 14 secondi):

open System
open System.IO

// need to change standard buffer, not to add an additional one
let stream = new StreamReader(Console.OpenStandardInput(4096))

let stdin = Seq.unfold (fun s -> if s = null then None else Some (s,stream.ReadLine())) <| stream.ReadLine()

let inline s2i (s : string) = Array.fold (fun a d -> a*10u + (uint32 d - uint32 '0') ) 0u <| s.ToCharArray()

let calc = 
    let fl = Seq.head stdin
    let [|_;ks|] = fl.Split(' ')
    let k = uint32 ks
    Seq.fold (fun a s -> if (s2i s) % k = 0u then a+1 else a) 0 <| Seq.skip 1 stdin

printf "%A" calc

Anche se il collo di bottiglia di questa versione è in realtà la conversione string -> uint32 (Cast Uint32 standard dalla stringa è anche più lento) la lettura stessa prende circa 2 sec (vs 6 sec di tempo totale) sul mio input di esempio (file ~ 100M) - ancora non è un grande risultato. Una volta s2i viene riscritto in stile imperativo, il totale di run-time può essere ridotto a 10 secondi lo Spoj:

let inline s2i (s : string) =
    let mutable a = 0u
    for i in 0..s.Length-1 do a <- a*10u + uint32 (s.Chars(i)) - uint32 '0'
    a

Altri suggerimenti

io in realtà non so, ma direi che la lettura di un dato carattere alla volta è male, e si dovrebbe leggere per esempio 4k in un buffer alla volta e quindi elaborare il buffer.

let buf =
    let raw = System.Console.OpenStandardInput()
    let bytebuf = new System.IO.BufferedStream(raw)
    new System.IO.StreamReader(bytebuf)

buf.Read()     // retrieves a single character as an int from the buffer
buf.ReadLine() // retrieves a whole line from the buffer
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top