Scanf.scanf "%d" (fun n ->
    let ab = Array.init n (fun _ -> Scanf.scanf " %d %d" (fun a b -> a, b)) in
    Array.sort (fun (a0, b0) (a1, b1) -> compare (a0 - b0) (a1 - b1)) ab;

    let rec loop i savings acc =
        if i = n then acc else
            let a, b = ab.(i) in
            if a <= b          then loop (i + 1) (savings + b - a) (acc + a) else
            if b - a > savings then loop (i + 1) (savings + a - b) (acc + a) else acc + savings
    in
    loop 0 0 0 |> Printf.printf "%d\n"
)