Home > プログラミング > ICPC by Haskell

ICPC by Haskell

なぜか D を飛ばしてICPC2005 Regional, Tokyo の問題Eを Haskell で.全生成して条件で filter して max とるという非常に美しい形に...

 -- Problem E in ACM/ICPC 2005 ASIA Regional Tokyo
 -- 2005/11/04   Brute Force (42 * 2^5)
import Control.Monad
import Debug.Trace
import List
main = getProblems >>= mapM_ (putStrLn.(\r -> if r < 0 then "-1" else show r).solve)
 
getProblems = 
    do
    n <- liftM (head.map read.words) getLine
    replicateM n getProblem
 
getProblem =
    do
    r <- getNum
    s <- liftM (head.map read.words) getLine
    ws <- replicateM s getNum
    return (r, ws)
    where 
    getNum = liftM (head.map read.words) getLine :: IO(Double)
 
solve :: (Double, [Double])->Double
solve (r, ws) = foldl max (-1.0).filter (<r).map(\(lw, rw)->lw+rw).concat.map genWidth.concat.map genTree.perm $ ws
 
data BTree a = Node a (BTree a) (BTree a)
             | Leaf a
genTree ] = [Leaf
genTree xs = [ Node (weight t + weight u) t u | i <- [1..length xs-1], t<-genTree (take i xs), u<-genTree (drop i xs)]
weight (Leaf x) = x
weight (Node x _ _) = x
genWidth (Leaf x) = [(0.0,0.0)]
genWidth (Node _ l r) = let
                        ls = genWidth l
                        rs = genWidth r
                        lw = weight l
                        rw = weight r
                        la = lw/(lw + rw)
                        ra = 1-la
                        in [x | (ll,lr)<-ls, (rl,rr)<-rs, x<-gen ll lr rl rr la ra]
gen ll lr rl rr la ra = dupFlip (max (la + ll) (rl-ra), max (ra + rr) (lr-la))
dupFlip (x,y) = [(x,y), (y,x)]
perm [] = []
perm ] = [[]
perm (x:xs) = [ take i y ++ (x:drop i y) | y <- perm xs, i <- [1..length xs]]
★下記に2つの英単語をスペースで区切って入力してください

Home > プログラミング > ICPC by Haskell

Search
Feeds

Page Top