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
Advertisements

May 25, 2011 - Posted by | Programming | ,

No comments yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: