Created
July 15, 2012 15:32
-
-
Save einblicker/3117471 to your computer and use it in GitHub Desktop.
PKU 2718 Smallest Difference
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let size = System.Console.ReadLine() |> int | |
let input = [| | |
for i = 0 to size - 1 do | |
yield System.Console.ReadLine().Split([|' '|]) |> Array.map int | |
|] | |
let rec permutations list taken = | |
seq { if Set.count taken = List.length list then yield [] else | |
for l in list do | |
if not (Set.contains l taken) then | |
for perm in permutations list (Set.add l taken) do | |
yield l::perm } | |
let xs = List.ofArray input.[0] | |
let toInt (xs : int list) = | |
let mutable total = 0 | |
for x in List.rev (List.map (fun x -> x) xs) do | |
total <- 10*total + x | |
total | |
seq { | |
for x in permutations xs Set.empty do | |
let l = Seq.length x/2 | |
if Seq.head x <> 0 then | |
if Seq.head (Seq.skip (l-1) x) <> 0 then | |
yield (Seq.take (l-1) x, Seq.skip (l-1) x) | |
if Seq.head (Seq.skip l x) <> 0 then | |
yield (Seq.take (l) x, Seq.skip (l) x) | |
if Seq.head (Seq.skip (l+1) x) <> 0 then | |
yield (Seq.take (l+1) x, Seq.skip (l+1) x) | |
} | |
|> Seq.map (fun (a, b) -> System.Math.Abs(toInt (List.ofSeq a) - toInt (List.ofSeq b))) | |
|> Seq.min | |
|> printfn "%A" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment