.

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
26
27
28
29
30
31
32
33
34
35
import Control.Monad
import Data.List
import Data.Maybe
import qualified Data.Map as M
import System.Environment

type NumMap = M.Map Integer Integer

isFree :: NumMap -> Integer -> Bool
isFree ma n = isNothing $ M.lookup n ma

place' :: Integer -> NumMap -> [NumMap]
place' n ma
    | isFree ma (firstFree + n) = [M.insert firstFree n . M.insert (firstFree + n) n $ ma]
    | otherwise = []
    where firstFree = fromJust . find (isFree ma) $ [0..]

place :: [Integer] -> NumMap -> [(Integer,NumMap)]
place xs ma = xs >>= \x -> do
  (,) x `fmap` place' x ma

placeAll :: [Integer] -> NumMap -> [NumMap]
placeAll [] ma = [ma]
placeAll xs ma = do
  (i,ma') <- place xs ma
  placeAll (delete i xs) ma'

isContinuous :: NumMap -> Bool
isContinuous ma = ks == take (length ks) [0..]
    where ks = M.keys ma

solutions :: [Integer] -> [[Integer]]
solutions xs = map M.elems . filter isContinuous . placeAll xs $ M.empty

main = mapM_ print . solutions . enumFromTo 0 . read . head =<< getArgs