INF = 10000 N = gets.to_i S = 1 << N B = N.times.map { gets.split.map(&:to_i) } dp = Array.new(N){ Array.new(S, INF) } # dp[i][s]はsを使用して最後の本がiの時の栞の最大間隔 N.times do |i| dp[i][1 << i] = 0 end (1 ... S).each do |s| used, unused = N.times.partition{ |i| (s & (1 << i)) > 0 } unused.each do |j| dp[j][s | (1 << j)] = used.inject(INF) do |m, i| a = dp[i][s] b = B[i][1] - B[i][0] + B[j][0] c = a > b ? a : b c < m ? c : m end end end puts N.times.inject(INF){|s,i| dp[i][S - 1] < s ? dp[i][S - 1] : s }