Add tags

Add tags to the following comment
条件を満す組み合せを生成するが、できるだけ余分なものを生成しないように
したつもり.

1 から n までの数から,k 個選ぶ組み合せのリストを生成する際に
採用されなかった残りの n-k 個の要素のリストをペアにするようにした
関数 comb を定義する.残りの部分には当然,既に採用した数ははいっていない.

comb' は和の制約を加え,さらに残りの組み合せ(リスト)が採用されたものより
辞書順で大きいものだけを採用するようにしてある.これによって,組み合せ
(リスト)のリスト同士の同一性をチェックしなくてすむ.

実行結果は以下のとおり.

% time ./magic 4
392
./magic 4  0.00s user 0.00s system 93% cpu 0.008 total
% time ./magic 5
3245664
./magic 5  47.19s user 0.40s system 99% cpu 47.590 total

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
module Main (main) where

import Data.List
import System.Environment

comb :: Int -> [a] -> [([a],[a])]
comb 0 xs = [([],xs)]
comb _ [] = []
comb k (x:xs) = [ (x:ys,zs) | (ys,zs) <- comb (k-1) xs ]
              ++[ (ys,x:zs) | (ys,zs) <- comb k     xs ]

comb' :: Int -> Int -> [Int] -> [([Int],[Int])]
comb' s 0 xs | s == 0    = [([],xs)]
             | otherwise = []
comb' _ _ []             = []
comb' s k (x:xs) = [ (x:ys,zs) | (ys,zs) <- comb (k-1) xs, s == x+sum ys ]

foo s k (acc,xs) = case unzip $ comb' s k xs of
  (yss,zss) -> zip (map (:acc) yss) zss
            
magic n = map (reverse . fst) $ iterate (concatMap (foo s n)) [([],ns)] !! n
  where ns = [1..n^2]
        s  = sum ns `div` n

main = print . length . magic . read . head =<< getArgs

Add tags

The input will be splited to tags with space.

Index

Feed

Other

Link

Pathtraq

loading...