My Weblog

Blog about programming and math

SPOJ 3375. Stamps

SPOJ 3375. Stamps is similar to TABLES problem. String will time out so use ByteString which is faster than String. Same source code but with ByteString.

import Data.List
import qualified Data.ByteString.Char8 as BS


solve :: [Integer] -> BS.ByteString
solve (n:_:xs) = if fst b < n then BS.pack "impossible\n" else BS.pack $ ( show.snd $ b ) ++ "\n"      where 
	xs' = sortBy ( \ a b -> compare b a ) xs
	b = foldl ( \(acc , cnt) x  -> if acc  < n then ( acc + x , cnt + 1 ) else ( acc , cnt ) ) (0,0) xs'


format::[BS.ByteString] ->[BS.ByteString]
format [] = []
format (x:y:xs) = ( BS.append ( BS.append x  (BS.pack " ") )  y ) : format xs

readInt:: BS.ByteString -> Integer
readInt x = case BS.readInteger x of 
		Just (y' , _ ) -> y'
		Nothing -> error " inseperable ints "

main = BS.interact $ BS.unlines . zipWith (BS.append) [ BS.append ( BS.append ( BS.pack $ "Scenario #") ( BS.pack.show $ i))  ( BS.pack ":\n") | i <-[1..] ]. map ( solve . map readInt . BS.words ) . format . tail . BS.lines

May 25, 2011 - Posted by | Programming | ,

No comments yet.

Leave a comment