A group of tourists is going to kayak and catamaran tour. A rented lorry has arrived to the boat depot to take kayaks and catamarans to the point of departure. It's known that all kayaks are of the same size (and each of them occupies the space of 1 cubic metre), and all catamarans are of the same size, but two times bigger than kayaks (and occupy the space of 2 cubic metres).Each waterborne vehicle has a particular carrying capacity, and it should be noted that waterborne vehicles that look the same can have different carrying capacities. Knowing the truck body volume and the list of waterborne vehicles in the boat depot (for each one its type and carrying capacity are known), find out such set of vehicles that can be taken in the lorry, and that has the maximum total carrying capacity. The truck body volume of the lorry can be used effectively, that is to say you can always put into the lorry a waterborne vehicle that occupies the space not exceeding the free space left in the truck body.

The first line contains a pair of integer numbers n and v (1 ≤ n ≤ 105; 1 ≤ v ≤ 109), where n is the number of waterborne vehicles in the boat depot, and v is the truck body volume of the lorry in cubic metres. The following n lines contain the information about the waterborne vehicles, that is a pair of numbers ti, pi (1 ≤ ti ≤ 2; 1 ≤ pi ≤ 104), where ti is the vehicle type (1 – a kayak, 2 – a catamaran), and pi is its carrying capacity. The waterborne vehicles are enumerated in order of their appearance in the input file.

In the first line print the maximum possible carrying capacity of the set. In the second line print a string consisting of the numbers of the vehicles that make the optimal set. If the answer is not unique, print any of them.

n,v = gets.split(" ").map{|x| x.to_i}
ts1 = Array.new
ts2 = Array.new
n.times do |i|
  t,p = gets.split(" ").map{|x| x.to_i}
  if t == 1
    ts1 << [i,p]
  else
    ts2 << [i,p]
  end
end
ts1.sort!{|a,b| -(a[1]<=>b[1])}
ts2.sort!{|a,b| -(a[1]<=>b[1])}
p2 = [(v-2)/2,ts2.size-1].min
p1 = [v-3-p2*2,ts1.size-1].min
while p1+1<ts1.size and p2>=0
  if p1+2<ts1.size
    if ts1[p1+1][1]+ts1[p1+2][1] > ts2[p2][1]
      p1+=2
      p2-=1
    else
      break
    end
  else
    if ts1[p1+1][1] > ts2[p2][1]
      p1+=1
      p2-=1
    else
      break
    end
  end
end
sum=0
ts = Array.new
0.upto(p1){|x| sum+=ts1[x][1];ts<<ts1[x][0]+1}
0.upto(p2){|x| sum+=ts2[x][1];ts<<ts2[x][0]+1}
puts sum
puts ts.join(" ")

num, max_size = gets.split.map(& :to_i)
kayak = []
catamaran = []
num.times do |index|
  t, p = gets.split.map(& :to_i)
  if t == 1
    kayak << [index + 1, p]
  else
    catamaran << [index + 1, p]
  end
end

kayak.sort! { |a, b| b[1] <=> a[1]  }
catamaran.sort! { |a, b| b[1] <=> a[1] }

max_c = [max_size / 2, catamaran.length].min
max_k = [max_size - 2 * max_c, kayak.length].min

while max_c > 0 && max_k <= kayak.length
  if max_k + 2 <= kayak.length #there are two more elements in the array
    if catamaran[max_c - 1][1] < (kayak[max_k][1] + kayak[max_k + 1][1])
      max_c = max_c - 1
      max_k = max_k + 2
    else
      break
    end
  else
    break
  end
end

ans_set = []
sum = 0
0.upto(max_c - 1) { |i| sum = sum + catamaran[i][1]; ans_set << catamaran[i][0] }
0.upto(max_k - 1) { |i| sum = sum + kayak[i][1]; ans_set << kayak[i][0] }
puts sum
puts ans_set.join(" ")

n, max = gets().split(" ").collect {|x| x.to_i}
kayaks = []
catemerons = []
n.times do |i|
  type, capacity = (gets().split(" ").collect {|x| x.to_i})
  if type == 1
    kayaks << [i, capacity]
  else
    catemerons << [i, capacity]
  end
end
kayaks.sort! {|x, y| y[1] <=> x[1]}
catemerons.sort! {|x, y| y[1] <=> x[1]}

max_c = [catemerons.length, (max/2).to_i].min
max_k = [kayaks.length, max].min

#puts "kayaks: #{kayaks.inspect}, catemerons: #{catemerons.inspect}, max_k:  #{max_k}, max_c: #{max_c}"

wt = 0
optimal = 0
selected_k = []
selected_c = []
i = 0
while (wt < max) && (i  < max_c) do
  if (wt + 2) <= max
    wt += 2
    optimal += catemerons[i][1]
    i += 1
  else
    break
  end
end

#puts "After catemerons, wt: #{wt}, i: #{i}"

j = 0
while (wt < max) && (j < max_k) do
  wt += 1
  optimal += kayaks[j][1]
  j += 1
end

#puts "After kayaks, wt: #{wt}, j: #{j}"

while (i > 0) && (j < max_k) do
  proposed_optimal1 = optimal - catemerons[i - 1][1] + kayaks[j][1]
  proposed_optimal2 = proposed_optimal1
  proposed_optimal2 += kayaks[j + 1][1] if (j < (max_k - 1))
  if proposed_optimal2 > optimal
    i -= 1
    j += 1
    optimal = proposed_optimal2
    j += 1 if (proposed_optimal2 > proposed_optimal1)
  else
    break
  end
end

puts optimal
(0..(i - 1)).each do |i| print "#{catemerons[i][0] + 1} " end
(0..(j - 1)).each do |j| print "#{kayaks[j][0] + 1} " end

n, max = gets().split(" ").collect {|x| x.to_i}
kayaks = []
catemerons = []
n.times do |i|
  type, capacity = (gets().split(" ").collect {|x| x.to_i})
  if type == 1
    kayaks << [i, capacity]
  else
    catemerons << [i, capacity]
  end
end
kayaks.sort! {|x, y| y[1] <=> x[1]}
catemerons.sort! {|x, y| y[1] <=> x[1]}

max_c = [catemerons.length, (max/2).to_i].min
max_k = [kayaks.length, max].min

#puts "kayaks: #{kayaks.inspect}, catemerons: #{catemerons.inspect}, max_k:  #{max_k}, max_c: #{max_c}"

wt = 0
optimal = 0
selected_k = []
selected_c = []
i = 0
while (wt < max) && (i  < max_c) do
  if (wt + 2) <= max
    wt += 2
    optimal += catemerons[i][1]
    i += 1
  else
    break
  end
end

#puts "After catemerons, wt: #{wt}, i: #{i}"

j = 0
while (wt < max) && (j < max_k) do
  wt += 1
  optimal += kayaks[j][1]
  j += 1
end

#puts "After kayaks, wt: #{wt}, j: #{j}"

while (i > 0) && (j < max_k) do
  proposed_optimal1 = optimal - catemerons[i - 1][1] + kayaks[j][1]
  proposed_optimal2 = proposed_optimal1
  proposed_optimal2 += kayaks[j + 1][1] if (j < (max_k - 1))
  if (proposed_optimal1 > optimal) || (proposed_optimal2 > optimal)
    i -= 1
    j += 1
    optimal = proposed_optimal1
    if (proposed_optimal2 > proposed_optimal1)
      j += 1
      optimal = proposed_optimal2
    end
  else
    break
  end
end

puts optimal
(0..(i - 1)).each do |i| print "#{catemerons[i][0] + 1} " end
(0..(j - 1)).each do |j| print "#{kayaks[j][0] + 1} " end

n,v = gets.split.map(&:to_i)

a1 = []
a2 = []

n.times do |i|
    t,q = gets.split.map(&:to_i)
    if t == 1 then a1 << [q, i]
    else a2 << [q, i]
    end
end

a2.sort!
a2.reverse!
a1.sort!
a1.reverse!

two = [v / 2, a2.length].min
total = 0
two.times do |i|
    total += a2[i][0]
end

one = [v - two * 2, a1.length].min
one.times do |i| total += a1[i][0] end

while two > 0 and one <= a1.length - 2 and a2[two - 1][0] < a1[one][0] + a1[one + 1][0] do
    total -= a2[two - 1][0]
    total += a1[one][0] + a1[one + 1][0];
    two -= 1
    one += 2
end

puts total
ans = []
two.times do |i| ans << 1 + a2[i][1] end
one.times do |i| ans << 1 + a1[i][1] end

puts ans * ' '

Vehicle = Struct.new(:index, :capacity)

class LorryLoader
  def self.load(lorry_volume, vehicle_registry)
    kayaks = []
    catamarans = []
    vehicle_registry.each.with_index do |vehicle, index|
      type, capacity = vehicle.split.map(&:to_i)
      kayaks << Vehicle.new(index + 1, capacity) if type == 1
      catamarans << Vehicle.new(index + 1, capacity) if type == 2
    end

    kayaks.sort_by! { |x| -x.capacity }
    catamarans.sort_by! { |x| -x.capacity }

    selected_vehicles = []
    total_capacity = volume = ki = ci = 0
    while (ki < kayaks.size || ci < catamarans.size) && volume < lorry_volume
      k_cap = ki < kayaks.size ? kayaks[ki].capacity : 0
      k_cap += kayaks[ki + 1].capacity if ki < kayaks.size - 1
      c_cap = ci < catamarans.size && lorry_volume - volume > 1 ? catamarans[ci].capacity : 0

      break if k_cap == 0 && c_cap == 0

      if (c_cap >= k_cap)
        selected_vehicles << catamarans[ci].index
        total_capacity += catamarans[ci].capacity
        volume += 2
        ci += 1
      else
        selected_vehicles << kayaks[ki].index
        total_capacity += kayaks[ki].capacity
        volume += 1
        ki += 1
      end
    end

    return total_capacity, selected_vehicles
  end
end

if __FILE__ == $0
  vehicle_count, lorry_volume = gets.split.map(&:to_i)
  vehicle_registry = []
  vehicle_count.times { vehicle_registry << gets }

  capacity, selected_vehicles = LorryLoader.load(lorry_volume, vehicle_registry)

  puts capacity
  puts selected_vehicles.join(' ')
end

def load_lorry(lorryVolume, kayaks, catamarans)
  kayaks.sort_by! { |x| x[1] * -1 }
  catamarans.sort_by! { |x| x[1] * -1 }

  capacity = volume = ki = ci = 0
  selected_vehicles = []
  while (ki < kayaks.length || ci < catamarans.length) && volume < lorryVolume
    c_value = ci < catamarans.length && lorryVolume - volume > 1 ? catamarans[ci][1] : 0
    k_value = ki < kayaks.length ? kayaks[ki][1] : 0

    k_value += kayaks[ki + 1][1] if ki < kayaks.length - 1

    break if k_value == 0 && c_value == 0

    if c_value > k_value
      capacity += catamarans[ci][1]
      selected_vehicles << catamarans[ci][0]
      ci += 1;
      volume += 2
    else
      capacity += kayaks[ki][1]
      selected_vehicles << kayaks[ki][0]
      ki += 1
      volume += 1
    end
  end

  return capacity, selected_vehicles
end

if __FILE__ == $0
  n, lorryVolume = gets.split.map(&:to_i)
  kayaks = []
  catamarans = []
  n.times do |i|
    t, c = gets.split.map(&:to_i)
    kayaks << [i + 1, c] if t == 1
    catamarans << [i + 1, c] if t == 2
  end

  capacity, selected_vehicles = load_lorry(lorryVolume, kayaks, catamarans)

  puts capacity
  puts selected_vehicles.join(" ")
end

def load_lorry(lorryVolume, vehicles)
  kayaks = []
  catamarans = []

  vehicles.each_with_index do |v, i|
    kayaks << [i + 1, v[1]] if v[0] == 1
    catamarans << [i + 1, v[1]] if v[0] == 2
  end

  kayaks.sort_by! { |x| x[1] * -1 }
  catamarans.sort_by! { |x| x[1] * -1 }

  capacity = volume = ki = ci = 0
  selected_vehicles = []
  while (ki < kayaks.length || ci < catamarans.length) && volume < lorryVolume
    c_value = ci < catamarans.length && lorryVolume - volume > 1 ? catamarans[ci][1] : 0
    k_value = ki < kayaks.length ? kayaks[ki][1] : 0

    k_value += kayaks[ki + 1][1] if ki < kayaks.length - 1

    break if k_value == 0 && c_value == 0

    if c_value > k_value
      capacity += catamarans[ci][1]
      selected_vehicles << catamarans[ci][0]
      ci += 1;
      volume += 2
    else
      capacity += kayaks[ki][1]
      selected_vehicles << kayaks[ki][0]
      ki += 1
      volume += 1
    end
  end

  return capacity, selected_vehicles
end

if __FILE__ == $0
  n, lorryVolume = gets.split.map(&:to_i)
  vehicles = []
  n.times { vehicles << gets.split.map(&:to_i) }

  capacity, selected_vehicles = load_lorry(lorryVolume, vehicles)

  puts capacity
  puts selected_vehicles.join(" ")
end

def load_lorry(lorryVolume, vehicles)
  kayaks = []
  catamarans = []

  vehicles.each_with_index do |v, i|
    kayaks << [i + 1, v[1]] if v[0] == 1
    catamarans << [i + 1, v[1]] if v[0] == 2
  end

  kayaks.sort! { |a, b| b[1] <=> a[1] }
  catamarans.sort! { |a, b| b[1] <=> a[1] }

  capacity = volume = ki = ci = 0
  selected_vehicles = []
  while (ki < kayaks.length || ci < catamarans.length) && volume < lorryVolume
    c_value = ci < catamarans.length && lorryVolume - volume > 1 ? catamarans[ci][1] : 0
    k_value = ki < kayaks.length ? kayaks[ki][1] : 0

    k_value += kayaks[ki + 1][1] if ki < kayaks.length - 1

    break if k_value == 0 && c_value == 0

    if c_value > k_value
      capacity += catamarans[ci][1]
      selected_vehicles << catamarans[ci][0]
      ci += 1;
      volume += 2
    else
      capacity += kayaks[ki][1]
      selected_vehicles << kayaks[ki][0]
      ki += 1
      volume += 1
    end
  end

  return capacity, selected_vehicles
end

if __FILE__ == $0
  n, lorryVolume = gets.split.map(&:to_i)
  vehicles = []
  n.times { vehicles << gets.split.map(&:to_i) }

  capacity, selected_vehicles = load_lorry(lorryVolume, vehicles)

  puts capacity
  puts selected_vehicles.join(" ")
end

def load_lorry(lorryVolume, vehicles)
  kayaks = []
  catamarans = []

  vehicles.each_with_index do |v, i|
    if (v[0] == 1)
      kayaks << [i + 1, v[1]]
    else
      catamarans << [i + 1, v[1]]
    end
  end

  kayaks.sort_by! { |x| x[1] * -1 }
  catamarans.sort_by! { |x| x[1] * -1 }

  volume = ki = ci = 0
  while ((ki < kayaks.length || ci < catamarans.length) && volume < lorryVolume)
    c_value = ci < catamarans.length && lorryVolume - volume > 1 ? catamarans[ci][1] : 0
    k_value = ki < kayaks.length ? kayaks[ki][1] : 0

    k_value += kayaks[ki + 1][1] if ki < kayaks.length - 1

    if (c_value > k_value)
      ci += 1;
      volume += 2
    else
      ki += 1
      volume += 1
    end
  end

  sel_vehicles = kayaks.take(ki) + catamarans.take(ci)
  return sel_vehicles.reduce(0) { |c, x| c + x[1] }, sel_vehicles.map { |x| x[0] }
end

if __FILE__ == $0
  n, lorryVolume = gets.split.map(&:to_i)
  vehicles = []
  n.times { vehicles << gets.split.map(&:to_i) }

  capacity, selected_vehicles = load_lorry(lorryVolume, vehicles)

  puts capacity
  puts selected_vehicles.join(" ")
end

n, v = gets.split.map(&:to_i)

kayaks = []
catamarans = []
n.times do |index|
	type, p = gets.split.map(&:to_i)
	if type == 1
		kayaks << [index + 1, p]
	else
		catamarans << [index + 1, p]
	end
end

kayaks.sort! { |e1, e2| e2[1] <=> e1[1] }
catamarans.sort! { |e1, e2| e2[1] <=> e1[1] }

possible_capacity = {}
max_c = [v / 2, catamarans.length].min
max_k = [v - 2 * max_c, kayaks.length].min
indexes = []
total = (0...max_c).inject(0) { |sum, value| sum + catamarans[value][1] } +
				(0...max_k).inject(0) { |sum, value| sum + kayaks[value][1] }

while max_c > 0 && max_k <= kayaks.length - 2 && catamarans[max_c - 1][1] < kayaks[max_k][1] + kayaks[max_k + 1][1]
	total -= catamarans[max_c - 1][1]
	total += kayaks[max_k][1] + kayaks[max_k + 1][1]
	max_c -= 1
	max_k += 2
end

indexes = []
max_c.times do |index|
	indexes << catamarans[index][0]
end
max_k.times do |index|
	indexes << kayaks[index][0]
end

puts total
puts indexes.join(' ')

n,v = gets.split(" ").map{|x| x.to_i}
ts = Array.new
n.times do |i|
  t,p = gets.split(" ").map{|x| x.to_i}
  ts << [i,t,p]
end
ts.sort!{|a,b| -(a[2]*2/a[1]<=>b[2]*2/b[1])}
max = 0
set = Array.new
ts.each_with_index do |t,i|
  break if v<=0
  applicable = false
  if v>2
    applicable = true
  else
    if v==t[1]
      applicable=true
    elsif v>t[1]
      if ts[i+1]
        if ts[i+1][1]==1
          applicable=true
        else
          nt = ts[i+1..-1].select{|x| x[1]==1}.first
          if nt
            if t[2]+nt[2]>ts[i+1][2]
              applicable=true
            end
          end
        end
      else
        applicable=true
      end
    end
  end
  if applicable
    set << t[0]+1
    v -= t[1]
    max += t[2]
  end
end
puts max
puts set.join(" ")

n,v = gets.split(" ").map{|x| x.to_i}
ts1 = Array.new
ts2 = Array.new
n.times do |i|
  t,p = gets.split(" ").map{|x| x.to_i}
  if t == 1
    ts1 << [i,p]
  else
    ts2 << [i,p]
  end
end
ts1.sort!{|a,b| -(a[1]<=>b[1])}
ts2.sort!{|a,b| -(a[1]<=>b[1])}
p2 = [(v-2)/2,ts2.size-1].min
p1 = n-3-p2*2
while p1+2<ts1.size and p2>=0
  if ts1[p1+1][1]+ts1[p1+2][1] > ts2[p2][1]
    p1+=2
    p2-=1
  else
    break
  end
end
sum=0
ts = Array.new
0.upto(p1){|x| sum+=ts1[x][1];ts<<ts1[x][0]+1}
0.upto(p2){|x| sum+=ts2[x][1];ts<<ts2[x][0]+1}
puts sum
puts ts.join(" ")

num, max_size = gets.split.map(& :to_i)
kayak = []
catamaran = []
num.times do |index|
  t, p = gets.split.map(& :to_i)
  if t == 1
    kayak << [index + 1, p]
  else
    catamaran << [index + 1, p]
  end
end

kayak.sort! { |a, b| b[1] <=> a[1]  }
catamaran.sort! { |a, b| b[1] <=> a[1] }

max_c = [max_size / 2, catamaran.length].min
max_k = [max_size - 2 * max_c, kayak.length].min

while max_c > 0 && max_k <= kayak.length
  if max_k + 2 <= kayak.length #there are two more elements in the array
    if catamaran[max_c - 1][1] < (kayak[max_k][1] + kayak[max_k + 1][1])
      max_c = max_c - 1
      max_k = max_k + 2
    else
      break
    end
  else
    if catamaran[max_c - 1][1] < kayak[max_k][1]
      max_c = max_c - 1
      max_k = max_k + 1
    else
      break
    end
  end
end

ans_set = []
sum = 0
0.upto(max_c - 1) { |i| sum = sum + catamaran[i][1]; ans_set << catamaran[i][0] }
0.upto(max_k - 1) { |i| sum = sum + kayak[i][1]; ans_set << kayak[i][0] }
puts sum
ans_set.sort!
puts ans_set.to_s[1..-2]

num, max_size = gets.split.map(& :to_i)
kayak = []
catamaran = []
num.times do |index|
  t, p = gets.split.map(& :to_i)
  if t == 1
    kayak << [index + 1, p]
  else
    catamaran << [index + 1, p]
  end
end

kayak.sort! { |a, b| b[1] <=> a[1]  }
catamaran.sort! { |a, b| b[1] <=> a[1] }

max_c = [max_size / 2, catamaran.length].min
max_k = [max_size - 2 * max_c, kayak.length].min

while max_c > 0 && max_k <= kayak.length && max_k > 0
  if max_k + 2 <= kayak.length #there are two more elements in the array
    if catamaran[max_c - 1][1] < (kayak[max_k][1] + kayak[max_k + 1][1])
      max_c = max_c - 1
      max_k = max_k + 2
    else
      break
    end
  else
    if catamaran[max_c - 1][1] < kayak[max_k][1]
      max_c = max_c - 1
      max_k = max_k + 1
    else
      break
    end
  end
end

ans_set = []
sum = 0
0.upto(max_c - 1) { |i| sum = sum + catamaran[i][1]; ans_set << catamaran[i][0] }
0.upto(max_k - 1) { |i| sum = sum + kayak[i][1]; ans_set << kayak[i][0] }
puts sum
puts ans_set.join(" ")

num, max_size = gets.split.map(& :to_i)
kayak = []
catamaran = []
num.times do |index|
  t, p = gets.split.map(& :to_i)
  if t == 1
    kayak << [index + 1, p]
  else
    catamaran << [index + 1, p]
  end
end

kayak.sort! { |a, b| b[1] <=> a[1]  }
catamaran.sort! { |a, b| b[1] <=> a[1] }

max_c = [max_size / 2, catamaran.length].min
max_k = [max_size - 2 * max_c, kayak.length].min

while max_c > 0 && max_k <= kayak.length
  if max_k + 2 <= kayak.length #there are two more elements in the array
    p "OK"
    if catamaran[max_c - 1][1] < (kayak[max_k][1] + kayak[max_k + 1][1])
      max_c = max_c - 1
      max_k = max_k + 2
    else
      break
    end
  else
    if catamaran[max_c - 1][1] < kayak[max_k][1]
      max_c = max_c - 1
      max_k = max_k + 1
    else
      break
    end
  end
end

ans_set = []
sum = 0
0.upto(max_c - 1) { |i| sum = sum + catamaran[i][1]; ans_set << catamaran[i][0] }
0.upto(max_k - 1) { |i| sum = sum + kayak[i][1]; ans_set << kayak[i][0] }
puts sum
ans_set.sort!
puts ans_set.to_s[1..-2]

n, max = gets().split(" ").collect {|x| x.to_i}
arr = []
i = 0
n.times do |i|
  arr << (gets().split(" ").collect {|x| x.to_i}).push(i + 1)
end
arr.sort! {|x, y| y[1] <=> x[1]}
#puts arr.inspect
wt = 0
optimal = 0
n = []
arr.each_with_index do |a, i|
  if ((wt + a[0]) <= max)
    optimal += a[1]
    n << a[2]
    wt += a[0]
    break if wt == max
  end
end
puts optimal
puts n.join(",")

n, max = gets().split(" ").collect {|x| x.to_i}
arr = []
i = 0
n.times do |i|
  arr << (gets().split(" ").collect {|x| x.to_i}).push(i + 1)
end
arr.sort! {|x, y| y[1] <=> x[1]}
#puts arr.inspect
wt = 0
optimal = 0
n = []
arr.each_with_index do |a, i|
  if ((wt + a[0]) <= max)
    optimal += a[1]
    n << a[2]
    wt += a[0]
    break if wt == max
  end
end
puts optimal
puts n.join(" ")

n, max = gets().split(" ").collect {|x| x.to_i}
arr = []
i = 0
n.times do |i|
  arr << (gets().split(" ").collect {|x| x.to_i}).push(i + 1)
end
arr.sort! {|x, y| y[1] <=> x[1]}
#puts arr.inspect
wt = 0
optimal = 0
n1 = []
n2 = []
arr.each_with_index do |a, i|
  if ((wt + a[0]) <= max)
    optimal += a[1]
    if a[0] == 1
      n1 << a[2]
    else
      n2 << a[2]
    end
    wt += a[0]
    break if wt == max
  end
end
puts optimal
puts n2.concat(n1).join(" ")

n, max = gets().split(" ").collect {|x| x.to_i}
kayaks = []
catemerons = []
n.times do |i|
  type, capacity = (gets().split(" ").collect {|x| x.to_i})
  if type == 1
    kayaks << [i, capacity]
  else
    catemerons << [i, capacity]
  end
end
kayaks.sort! {|x, y| y[1] <=> x[1]}
catemerons.sort! {|x, y| y[1] <=> x[1]}

max_c = [catemerons.length, (max/2).to_i].min
max_k = [kayaks.length, max].min

puts "kayaks: #{kayaks.inspect}, catemerons: #{catemerons.inspect}, max_k:  #{max_k}, max_c: #{max_c}"

wt = 0
optimal = 0
selected_k = []
selected_c = []
i = 0
while (wt < max) && (i  < max_c) do
  if (wt + 2) <= max
    wt += 2
    optimal += catemerons[i][1]
    i += 1
  else
    break
  end
end

#puts "After catemerons, wt: #{wt}, i: #{i}"

j = 0
while (wt < max) && (j < max_k) do
  wt += 1
  optimal += kayaks[j][1]
  j += 1
end

#puts "After kayaks, wt: #{wt}, j: #{j}"

while (i > 0) && (j < max_k) do
  proposed_optimal1 = optimal - catemerons[i - 1][1] + kayaks[j][1]
  proposed_optimal2 = proposed_optimal1
  proposed_optimal2 += kayaks[j + 1][1] if (j < (max_k - 1))
  if (proposed_optimal1 > optimal) || (proposed_optimal2 > optimal)
    i -= 1
    j += 1
    optimal = proposed_optimal1
    if (proposed_optimal2 > proposed_optimal1)
      j += 1
      optimal = proposed_optimal2
    end
  else
    break
  end
end

puts optimal
(0..(i - 1)).each do |i| print "#{catemerons[i][0] + 1} " end
(0..(j - 1)).each do |j| print "#{kayaks[j][0] + 1} " end

n,v = gets.split.map(&:to_i)

a1 = []
a2 = []

n.times do |i|
    t,q = gets.split.map(&:to_i)
    if t == 1 then a1 << [q, i]
    else a2 << [q, i]
    end
end

a2.sort!
a2.reverse!
a1.sort!
a1.reverse!

one = 0
two = [v / 2, a2.length].min
total = 0
two.times do |i|
    total += a2[i][0]
end

while two > 0 and one < a1.length - 2 and a2[two - 1][0] < a1[one][0] + a1[one + 1][0] do
    total -= a2[two - 1][0]
    total += a1[one][0] + a1[one + 1][0];
    two -= 1
    one += 2
end

puts total
ans = []
two.times do |i| ans << 1 + a2[i][1] end
one.times do |i| ans << 1 + a1[i][1] end

puts ans * ' '

Vehicle = Struct.new(:index, :capacity)

class LorryLoader
  def self.load(lorry_volume, vehicle_registry)
    kayaks = []
    catamarans = []

    vehicle_registry.each.with_index do |vehicle, index|
      type, capacity = vehicle.split.map(&:to_i)
      if type == 1
        kayaks << Vehicle.new(index + 1, capacity)
      elsif
        catamarans << Vehicle.new(index + 1, capacity)
      end
    end

    kayaks.sort_by! { |x| -x.capacity }
    catamarans.sort_by! { |x| -x.capacity }

    selected_vehicles = []
    total_capacity = volume = ki = ci = 0
    while (ki < kayaks.size || ci < catamarans.size) && volume < lorry_volume
      k_cap = ki < kayaks.size ? kayaks[ki].capacity : 0
      k_cap += (ki < kayaks.size - 1 ? kayaks[ki - 1].capacity : 0)
      c_cap = ci < catamarans.size && lorry_volume - volume > 1 ? catamarans[ci].capacity : 0

      break if k_cap == 0 && c_cap == 0

      if (c_cap >= k_cap)
        selected_vehicles << catamarans[ci].index
        total_capacity += catamarans[ci].capacity
        volume += 2
        ci += 1
      else
        selected_vehicles << kayaks[ki].index
        total_capacity += kayaks[ki].capacity
        volume += 1
        ki += 1
      end
    end

    return total_capacity, selected_vehicles
  end
end

if __FILE__ == $0
  vehicle_count, lorry_volume = gets.split.map(&:to_i)
  vehicle_registry = []
  vehicle_count.times { vehicle_registry << gets }

  capacity, selected_vehicles = LorryLoader.load(lorry_volume, vehicle_registry)

  puts capacity
  puts selected_vehicles.join(' ')
end

def load_lorry(lorryVolume, vehicles)
  kayaks = []
  catamarans = []

  vehicles.each_with_index do |v, i|
    kayaks << [i + 1, v[1]] if v[0] == 1
    catamarans << [i + 1, v[1]] if v[0] == 2
  end

  kayaks.sort!
  catamarans.sort!

  capacity = volume = ki = ci = 0
  selected_vehicles = []
  while (ki < kayaks.length || ci < catamarans.length) && volume < lorryVolume
    c_value = ci < catamarans.length && lorryVolume - volume > 1 ? catamarans[ci][1] : 0
    k_value = ki < kayaks.length ? kayaks[ki][1] : 0

    k_value += kayaks[ki + 1][1] if ki < kayaks.length - 1

    break if k_value == 0 && c_value == 0

    if c_value > k_value
      capacity += catamarans[ci][1]
      selected_vehicles << catamarans[ci][0]
      ci += 1;
      volume += 2
    else
      capacity += kayaks[ki][1]
      selected_vehicles << kayaks[ki][0]
      ki += 1
      volume += 1
    end
  end

  return capacity, selected_vehicles
end

if __FILE__ == $0
  n, lorryVolume = gets.split.map(&:to_i)
  vehicles = []
  n.times { vehicles << gets.split.map(&:to_i) }

  capacity, selected_vehicles = load_lorry(lorryVolume, vehicles)

  puts capacity
  puts selected_vehicles.join(" ")
end

n, v = gets.split.map(&:to_i)

kayaks = []
catamarans = []

n.times do
	vehicle_info = gets.split.map(&:to_i)
	if vehicle_info[0] == 1
		kayaks << vehicle_info[1]
	else
		catamarans << vehicle_info[1]
	end
end

kayaks.sort! { |e1, e2| e2 <=> e1 }
catamarans.sort! { |e1, e2| e2 <=> e1 }

possible_capacity = []
max_catamarans = v / 2
max_kayaks = [v, kayaks.length].min
(0..max_catamarans).each do |num_of_c|
	next if (num_of_k = v - 2 * num_of_c) > max_kayaks
	capacity = kayaks[0...num_of_k].inject(0) { |sum, value| sum + value } +
						 catamarans[0...num_of_c].inject(0) { |sum, value| sum + value }
	count = num_of_k + num_of_c
	possible_capacity << [capacity, count]
end

puts possible_capacity

n, v = gets.split.map(&:to_i)

kayaks = []
catamarans = []
n.times do |index|
	type, p = gets.split.map(&:to_i)
	if type == 1
		kayaks << [index + 1, p]
	else
		catamarans << [index + 1, p]
	end
end

kayaks.sort! { |e1, e2| e2[1] <=> e1[1] }
catamarans.sort! { |e1, e2| e2[1] <=> e1[1] }

possible_capacity = {}
max_c = [v / 2, catamarans.length].min
max_k = [v - 2 * max_c, kayaks.length].min
indexes = []
total = (0...max_c).inject(0) { |sum, value| sum + catamarans[value][1] } +
				(0...max_k).inject(0) { |sum, value| sum + kayaks[value][1] }
puts total
while max_c > 0 && max_k <= kayaks.length - 2 && catamarans[max_c - 1][1] < kayaks[max_k][1] + kayaks[max_k + 1][1]
	total -= catamarans[max_c - 1][1]
	total += kayaks[max_k][1] + kayaks[max_k + 1][1]
	max_c -= 1
	max_k += 2
end

indexes = []
max_c.times do |index|
	indexes << catamarans[index][0]
end
max_k.times do |index|
	indexes << kayaks[index][0]
end

puts total
puts indexes.join(' ')

n, v = gets.split.map(&:to_i)

kayaks = []
catamarans = []
n.times do |index|
	type, p = gets.split.map(&:to_i)
	if type == 1
		kayaks << [index + 1, p]
	else
		catamarans << [index + 1, p]
	end
end

kayaks.sort! { |e1, e2| e2[1] <=> e1[1] }
catamarans.sort! { |e1, e2| e2[1] <=> e1[1] }

possible_capacity = {}
max_c = [v / 2, catamarans.length].min
max_k = [v - 2 * max_c, kayaks.length].min
indexes = []
total = (0...max_c).inject(0) { |sum, value| sum + catamarans[value][1] } +
				(0...max_k).inject(0) { |sum, value| sum + kayaks[value][1] }

while max_c > 0 && max_k <= kayaks.length - 2 && catamarans[max_c - 1][0] < kayaks[max_k][0] + kayaks[max_k + 1][0]
	total -= catamarans[max_c - 1][0]
	total += kayaks[max_k][0] + kayaks[max_k + 1][0]
	max_c -= 1
	max_k += 2
end

indexes = []
max_c.times do |index|
	indexes << catamarans[index][0]
end
max_k.times do |index|
	indexes << kayaks[index][0]
end

puts total
puts indexes.join(' ')

n, v = gets.split.map(&:to_i)

kayaks = []
catamarans = []
n.times do |index|
	type, p = gets.split.map(&:to_i)
	if type == 1
		kayaks << [index + 1, p]
	else
		catamarans << [index + 1, p]
	end
end

kayaks.sort! { |e1, e2| e2[1] <=> e1[1] }
catamarans.sort! { |e1, e2| e2[1] <=> e1[1] }

possible_capacity = {}
max_c = [v / 2, catamarans.length].min
max_k = [v - 2 * max_c, kayaks.length].min
indexes = []
total = (0...max_c).inject(0) { |sum, value| sum + catamarans[value][1] } +
				(0...max_k).inject(0) { |sum, value| sum + kayaks[value][1] }

while max_c > 0 && max_k <= kayaks.length - 2 && catamarans[max_c - 1][1] < kayaks[max_k][1] + kayaks[max_k + 1][1]
	total -= catamarans[max_c - 1][0]
	total += kayaks[max_k][0] + kayaks[max_k + 1][0]
	max_c -= 1
	max_k += 2
end

indexes = []
max_c.times do |index|
	indexes << catamarans[index][0]
end
max_k.times do |index|
	indexes << kayaks[index][0]
end

puts total
puts indexes.join(' ')

n, v = gets.split.map(&:to_i)

kayaks = []
catamarans = []
n.times do |index|
	type, p = gets.split.map(&:to_i)
	if type == 1
		kayaks << [index + 1, p]
	else
		catamarans << [index + 1, p]
	end
end

kayaks.sort! { |e1, e2| e2[1] <=> e1[1] }
catamarans.sort! { |e1, e2| e2[1] <=> e1[1] }

possible_capacity = {}
max_c = [v / 2, catamarans.length].min
max_k = [v - 2 * max_c, kayaks.length].min
indexes = []
total = (0...max_c).inject(0) { |sum, value| sum + catamarans[value][1] } +
				(0...max_k).inject(0) { |sum, value| sum + kayaks[value][1] }

while max_c > 0 && max_k <= kayaks.length - 2 && catamarans[max_c - 1][0] < kayaks[max_k][0] + kayaks[max_k + 1][0]
	total -= catamarans[max_c - 1][0]
	total += kayaks[max_k][0] + kayaks[max_k + 1][0]
	max_c -= 1
	max_k += 2
end

indexes = []
max_k.times do |index|
	indexes << kayaks[index][0]
end
max_c.times do |index|
	indexes << catamarans[index][0]
end

puts total
puts indexes.join(' ')

n, v = gets.split.map(&:to_i)

kayaks = []
catamarans = []

n.times do
	vehicle_info = gets.split.map(&:to_i)
	if vehicle_info[0] == 1
		kayaks << vehicle_info[1]
	else
		catamarans << vehicle_info[1]
	end
end

kayaks.sort! { |e1, e2| e2 <=> e1 }
catamarans.sort! { |e1, e2| e2 <=> e1 }

possible_capacity = {}
max_catamarans = v / 2
(0..max_catamarans).each do |num_of_c|
	next if (num_of_k = v - 2 * num_of_c) > kayaks.length
	capacity = kayaks[0...num_of_k].inject(0) { |sum, value| sum + value } +
						 catamarans[0...num_of_c].inject(0) { |sum, value| sum + value }
	possible_capacity[capacity] = [num_of_k, num_of_c]
end

max_capacity = possible_capacity.max
puts max_capacity[0]
puts ([1] * max_capacity[1][0] + [2] * max_capacity[1][1]).join(' ')


Polycarp remembered the $$$2020$$$-th year, and he is happy with the arrival of the new $$$2021$$$-th year. To remember such a wonderful moment, Polycarp wants to represent the number $$$n$$$ as the sum of a certain number of $$$2020$$$ and a certain number of $$$2021$$$.For example, if:   $$$n=4041$$$, then the number $$$n$$$ can be represented as the sum $$$2020 + 2021$$$;  $$$n=4042$$$, then the number $$$n$$$ can be represented as the sum $$$2021 + 2021$$$;  $$$n=8081$$$, then the number $$$n$$$ can be represented as the sum $$$2020 + 2020 + 2020 + 2021$$$;  $$$n=8079$$$, then the number $$$n$$$ cannot be represented as the sum of the numbers $$$2020$$$ and $$$2021$$$. Help Polycarp to find out whether the number $$$n$$$ can be represented as the sum of a certain number of numbers $$$2020$$$ and a certain number of numbers $$$2021$$$.

The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. Each test case contains one integer $$$n$$$ ($$$1 \leq n \leq 10^6$$$) — the number that Polycarp wants to represent as the sum of the numbers $$$2020$$$ and $$$2021$$$.

For each test case, output on a separate line:    "YES" if the number $$$n$$$ is representable as the sum of a certain number of $$$2020$$$ and a certain number of $$$2021$$$;  "NO" otherwise.  You can output "YES" and "NO" in any case (for example, the strings yEs, yes, Yes and YES will be recognized as positive).

gets.to_i.times do
  n = gets.to_i
  puts n % 2020 <= n / 2020 ? "YES" : "NO"
end

require 'set'
s = Set.new

flag = 0

val1 = 1000000/2020;
val2 = 1000000/2021;

for i in (0..val1)
    for j in (0..val2)
        temp = i*2020+j*2021;
        s << temp;
    end
end

n = gets.chomp.to_i;
while n != 0
    n = n-1;
    value = gets.chomp.to_i;
    if s.include?(value)
        puts "YES"
    else
        puts "NO"
    end
end

MAX_N = 10**6 + 5
flag = [false] * MAX_N
flag[0] = true
(0...MAX_N).each do |i|
	if flag[i]
		flag[i + 2020] = true if i + 2020 < MAX_N
		flag[i + 2021] = true if i + 2021 < MAX_N
	end
end

gets.to_i.times do
	n = gets.to_i
	puts flag[n] ? 'YES' : 'NO'
end

t = gets.to_i
t.times do
  n = gets.to_i
  puts (n % 2020 <= n / 2020) ? "YES" : "NO"
end

tcases = gets.chomp.to_i
def solve()
  n = gets.chomp.to_i
  q = n / 2020
  r = n % 2020
  puts (r <= q) ? "YES" : "NO"
end
tcases.times do solve() end

t = gets.chomp.to_i
# arr = []
t.times do
    n = gets.chomp.to_i
    ok = false
    0.upto(500) do |i|
        ans = n - i * 2021
        #  p ans
        if ans >= 0
            amari = ans % 2020
            if amari == 0
                puts "YES"
                # arr << i
                ok = true
                break
            end
        else
            break
        end
    end
    if ok == false
        puts "NO"
    end
end

t=gets.to_i
t.times{
	n = gets.to_i
	if n<2020
		puts "NO"
	else
		puts n%2020 <= n/2020? "YES" : "NO"
	end
}

gets.to_i.times do
  n = gets.to_i
  puts n % 2020 >= n / 2020 ? "YES" : "NO"
end


As their story unravels, a timeless tale is told once again...Shirahime, a friend of Mocha's, is keen on playing the music game Arcaea and sharing Mocha interesting puzzles to solve. This day, Shirahime comes up with a new simple puzzle and wants Mocha to solve them. However, these puzzles are too easy for Mocha to solve, so she wants you to solve them and tell her the answers. The puzzles are described as follow.There are $$$n$$$ squares arranged in a row, and each of them can be painted either red or blue.Among these squares, some of them have been painted already, and the others are blank. You can decide which color to paint on each blank square.Some pairs of adjacent squares may have the same color, which is imperfect. We define the imperfectness as the number of pairs of adjacent squares that share the same color.For example, the imperfectness of "BRRRBBR" is $$$3$$$, with "BB" occurred once and "RR" occurred twice.Your goal is to minimize the imperfectness and print out the colors of the squares after painting.

Each test contains multiple test cases.  The first line contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Each test case consists of two lines. The first line of each test case contains an integer $$$n$$$ ($$$1\leq n\leq 100$$$) — the length of the squares row. The second line of each test case contains a string $$$s$$$ with length $$$n$$$, containing characters 'B', 'R' and '?'. Here 'B' stands for a blue square, 'R' for a red square, and '?' for a blank square.

For each test case, print a line with a string only containing 'B' and 'R', the colors of the squares after painting, which imperfectness is minimized. If there are multiple solutions, print any of them.

NoteIn the first test case, if the squares are painted "BRRBRBR", the imperfectness is $$$1$$$ (since squares $$$2$$$ and $$$3$$$ have the same color), which is the minimum possible imperfectness.

gets.to_i.times do
  n=gets.to_i
  s=gets.chomp.chars
  q=""
  t=0
  s.each.with_index do |ss,i|
    if q==""
      if ss=="?"
        t+=1
      elsif ss=="B"
        s[0,i]=["R"]*(i%2)+["B","R"]*(i/2)
        q="B"
      elsif ss=="R"
        s[0,i]=["B"]*(i%2)+["R","B"]*(i/2)
        q="R"
      end
    elsif q=="B"
      if ss=="?"
        s[i]="R"
        q="R"
      elsif ss=="R"
        q="R"
      end
    else
      if ss=="?"
        s[i]="B"
        q="B"
      elsif ss=="B"
        q="B"
      end
    end
  end
  if q==""
    s=["R"]*(n%2)+["B","R"]*(n/2)
  end
  puts s.join
end

END { load __FILE__ unless $stdin.eof? }

t = gets.to_i
t.times do

n = gets.to_i
s = gets.chomp.chars.map! { |c| c == "B" ? 1 : c == "R" ? 2 : 0 }

i = s.index(&:nonzero?) || n
c = s[i] || 1
i.times.reverse_each do |k|
  s[k] = (c ^= 3)
end

while i < n
  i += 1
  j = (i...n).find { |k| s[k] != 0 } || n

  c = s[i-1]
  (i...j).each { |k| s[k] = (c ^= 3) }

  i = j
end

puts (s * "").tr("12", "BR")

end


Consider all binary strings of length $$$m$$$ ($$$1 \le m \le 60$$$). A binary string is a string that consists of the characters 0 and 1 only. For example, 0110 is a binary string, and 012aba is not. Obviously, there are exactly $$$2^m$$$ such strings in total.The string $$$s$$$ is lexicographically smaller than the string $$$t$$$ (both have the same length $$$m$$$) if in the first position $$$i$$$ from the left in which they differ, we have $$$s[i] < t[i]$$$. This is exactly the way strings are compared in dictionaries and in most modern programming languages when comparing them in a standard way. For example, the string 01011 is lexicographically smaller than the string 01100, because the first two characters are the same, and the third character in the first string is less than that in the second.We remove from this set $$$n$$$ ($$$1 \le n \le \min(2^m-1, 100)$$$) distinct binary strings $$$a_1, a_2, \ldots, a_n$$$, each of length $$$m$$$. Thus, the set will have $$$k=2^m-n$$$ strings. Sort all strings of the resulting set in lexicographical ascending order (as in the dictionary).We number all the strings after sorting from $$$0$$$ to $$$k-1$$$. Print the string whose index is $$$\lfloor \frac{k-1}{2} \rfloor$$$ (such an element is called median), where $$$\lfloor x \rfloor$$$ is the rounding of the number down to the nearest integer.For example, if $$$n=3$$$, $$$m=3$$$ and $$$a=[$$$010, 111, 001$$$]$$$, then after removing the strings $$$a_i$$$ and sorting, the result will take the form: $$$[$$$000, 011, 100, 101, 110$$$]$$$. Thus, the desired median is 100.

The first line contains an integer $$$t$$$ ($$$1 \le t \le 1000$$$) — the number of test cases. Then, $$$t$$$ test cases follow. The first line of each test case contains integers $$$n$$$ ($$$1 \le n \le \min(2^m-1, 100)$$$) and $$$m$$$ ($$$1 \le m \le 60$$$), where $$$n$$$ is the number of strings to remove, and $$$m$$$ is the length of binary strings. The next $$$n$$$ lines contain $$$a_1, a_2, \ldots, a_n$$$ — distinct binary strings of length $$$m$$$. The total length of all given binary strings in all test cases in one test does not exceed $$$10^5$$$.

Print $$$t$$$ answers to the test cases. For each test case, print a string of length $$$m$$$ — the median of the sorted sequence of remaining strings in the corresponding test case.

NoteThe first test case is explained in the statement.In the second test case, the result after removing strings and sorting is $$$[$$$001, 010, 101, 110$$$]$$$. Therefore, the desired median is 010.

gets.to_i.times do
	n, m = gets.split.map(&:to_i)
	a = (1..n).map { gets.chomp.to_i(2) }
	puts (0...2**m).bsearch { |i|
			i + 1 - a.count { _1 <= i } >= (2**m - n + 1) / 2
	     }.to_s(2).rjust(m, '0')
end


Sometimes it is not easy to come to an agreement in a bargain. Right now Sasha and Vova can't come to an agreement: Sasha names a price as high as possible, then Vova wants to remove as many digits from the price as possible. In more details, Sasha names some integer price $$$n$$$, Vova removes a non-empty substring of (consecutive) digits from the price, the remaining digits close the gap, and the resulting integer is the price.For example, is Sasha names $$$1213121$$$, Vova can remove the substring $$$1312$$$, and the result is $$$121$$$.It is allowed for result to contain leading zeros. If Vova removes all digits, the price is considered to be $$$0$$$.Sasha wants to come up with some constraints so that Vova can't just remove all digits, but he needs some arguments supporting the constraints. To start with, he wants to compute the sum of all possible resulting prices after Vova's move.Help Sasha to compute this sum. Since the answer can be very large, print it modulo $$$10^9 + 7$$$.

The first and only line contains a single integer $$$n$$$ ($$$1 \le n < 10^{10^5}$$$).

In the only line print the required sum modulo $$$10^9 + 7$$$.

class Integer
  def mod_pow(n, mod)
    x = self
    res = 1

    while n > 0
      res = res * x % mod if n[0] == 1
      x = x * x % mod
      n >>= 1
    end

    res
  end

  def mod_inverse(mod)
    mod_pow(mod - 2, mod)
  end
end

N = gets.chomp
n = N.size
MOD = 10 ** 9 + 7
inv = 10.mod_inverse(MOD)
base = 10.pow(n - 1, MOD)
ans = 0
sum = 0

N.chars.map(&:to_i).each.with_index do |x, k|
  # add left
  s = k * (k + 1) / 2
  ans += s * (base * x)
  ans %= MOD

  # add right
  ans += sum * (n - k)
  ans %= MOD

  sum *= inv
  sum %= MOD

  base *= inv
  base %= MOD
  sum += x * base
  sum %= MOD
end

puts ans


Orac is studying number theory, and he is interested in the properties of divisors.For two positive integers $$$a$$$ and $$$b$$$, $$$a$$$ is a divisor of $$$b$$$ if and only if there exists an integer $$$c$$$, such that $$$a\cdot c=b$$$.For $$$n \ge 2$$$, we will denote as $$$f(n)$$$ the smallest positive divisor of $$$n$$$, except $$$1$$$.For example, $$$f(7)=7,f(10)=2,f(35)=5$$$.For the fixed integer $$$n$$$, Orac decided to add $$$f(n)$$$ to $$$n$$$. For example, if he had an integer $$$n=5$$$, the new value of $$$n$$$ will be equal to $$$10$$$. And if he had an integer $$$n=6$$$, $$$n$$$ will be changed to $$$8$$$.Orac loved it so much, so he decided to repeat this operation several times.Now, for two positive integers $$$n$$$ and $$$k$$$, Orac asked you to add $$$f(n)$$$ to $$$n$$$ exactly $$$k$$$ times (note that $$$n$$$ will change after each operation, so $$$f(n)$$$ may change too) and tell him the final value of $$$n$$$.For example, if Orac gives you $$$n=5$$$ and $$$k=2$$$, at first you should add $$$f(5)=5$$$ to $$$n=5$$$, so your new value of $$$n$$$ will be equal to $$$n=10$$$, after that, you should add $$$f(10)=2$$$ to $$$10$$$, so your new (and the final!) value of $$$n$$$ will be equal to $$$12$$$.Orac may ask you these queries many times.

The first line of the input is a single integer $$$t\ (1\le t\le 100)$$$: the number of times that Orac will ask you. Each of the next $$$t$$$ lines contains two positive integers $$$n,k\ (2\le n\le 10^6, 1\le k\le 10^9)$$$, corresponding to a query by Orac. It is guaranteed that the total sum of $$$n$$$ is at most $$$10^6$$$.

Print $$$t$$$ lines, the $$$i$$$-th of them should contain the final value of $$$n$$$ in the $$$i$$$-th query by Orac.

NoteIn the first query, $$$n=5$$$ and $$$k=1$$$. The divisors of $$$5$$$ are $$$1$$$ and $$$5$$$, the smallest one except $$$1$$$ is $$$5$$$. Therefore, the only operation adds $$$f(5)=5$$$ to $$$5$$$, and the result is $$$10$$$.In the second query, $$$n=8$$$ and $$$k=2$$$. The divisors of $$$8$$$ are $$$1,2,4,8$$$, where the smallest one except $$$1$$$ is $$$2$$$, then after one operation $$$8$$$ turns into $$$8+(f(8)=2)=10$$$. The divisors of $$$10$$$ are $$$1,2,5,10$$$, where the smallest one except $$$1$$$ is $$$2$$$, therefore the answer is $$$10+(f(10)=2)=12$$$.In the third query, $$$n$$$ is changed as follows: $$$3 \to 6 \to 8 \to 10 \to 12$$$.

def minimum(x)
  for i in 2..x do
    return i if x % i == 0
  end
end

t = gets.chomp.to_i

t.times do
  n, k = gets.chomp.split(' ').collect(&:to_i)
  puts minimum(n) + n + (2*(k-1))
end

def ans(n, k)
    # 偶数 为2， 加2后还是偶数， 所以 n + 2k
    # 奇数 第一个为奇书， 相加后也为偶数 n + first.x + 2 (k-1)
    if n & 0x1 == 0
        return n + 2 * k
    end

    d = 3

    while d <= Math.sqrt(n)
        n % d  == 0 and return n + d + 2 *(k-1)
        d += 2
    end

    return n + n + 2 * (k-1)
end

line = gets().to_i

line.times {
    (n,k) = gets.scan(/\d+/).map(&:to_i)
    puts ans(n,k)
}

def ans(n, k)
    # 偶数 为2， 加2后还是偶数， 所以 n + 2k
    # 奇数 第一个为奇书， 相加后也为偶数 n + first.x + 2 (k-1)
    if n & 0x1 == 0
        return n + 2 * k
    end

    d = 3
    while d < n
        n % d  == 0 and break
        d += 2
    end

    return n + d + 2*(k-1)
end

line = gets().to_i

line.times {
    (n,k) = gets.scan(/\d+/).map(&:to_i)
    puts ans(n,k)
}

t = gets.to_i

1.upto t do
  c = p = 0
  n, k = gets.split.map(&:to_i)
  if n % 2 == 0
    n += k*2
  else
    2.upto Math.sqrt(n+1).to_i do |i|
      if n % i == 0
        n += i
        p = 1
        break
      end
    end
    if p == 0
      n += n
    end
    n += (k-1)*2
  end
  puts n
end

t = gets.to_i

1.upto t do
  c = 0
  n, k = gets.split.map(&:to_i)
  if n % 2 == 0
    n += k*2
  else
    3.upto n do |i|
      if n % i == 0
        n += i
        break
      end
    end
    n += (k-1)*2
  end
  puts n
end

require 'prime'
gets.to_i.times do
    n, k=gets.split.map &:to_i
    f=n.prime_division[0][0]
    puts n+f+2*(k-1)
end

#exec({'RUBY_THREAD_VM_STACK_SIZE'=>'100000000'},'/usr/bin/ruby', $0) if !ENV['RUBY_THREAD_VM_STACK_SIZE']
require 'prime'

def inpf() a=gets.chomp.split(" ").map(&:to_f)end

def inps() a=gets.chomp.split(" ")end

def copy(a) Marshal.load(Marshal.dump(a)) end

def kaijo(n,r = 10**9+7)(n < 2)? 1 : (2..n).inject{|memo,u|memo=(memo*u)%r} end

def na(n,d=0) Array.new(n,d)end

def na2(n,m,d=0) Array.new(n){Array.new(m,d)}end

def na3(n,m,l,d=0) Array.new(n){Array.new(m){Array.new(l,d)}}end

def inp() a=gets.chomp.split(" ").map(&:to_i)end

def r_up(a, b) (a+b-1)/b end

def sum(a) a.inject(:+) end

def big(a,b) return (a>b)? a:b end

def small(a,b) return (a<b)? a:b end

n = inp[0]
d = []
n.times do
  d <<inp
end
d.each do |a|
  if (a[0].even?)
    p a[0] + 2*a[1]
  else
    p a[0] + a[0].prime_division[0][0] + 2*(a[1]-1)
  end
end

def f(n)
  2.upto(n) { |i| return i if n.modulo(i).zero? }
end

gets.to_i.times do
  n, k = gets.split(' ').map(&:to_i)

  k.downto(1) do |kk|
    ff = f(n)

    if ff == 2
      n += kk * ff
      break
    end

    n += ff
  end

  puts n
end

def ans(n, k)
    # 偶数 为2， 加2后还是偶数， 所以 n + 2k
    # 奇数 第一个为奇书， 相加后也为偶数 n + first.x + 2 (k-1)
    if n & 0x1 == 0
        return n + 2 * k
    end

    d = 3
    while d < n
        n % d  == 0 and break
        d += n
    end

    return n + d + 2*(k-1)
end

line = gets().to_i

line.times {
    (n,k) = gets.scan(/\d+/).map(&:to_i)
    puts ans(n,k)
}

t = gets.to_i

1.upto t do
  c = p = 0
  n, k = gets.split.map(&:to_i)
  if n % 2 == 0
    n += k*2
  else
    2.upto Math.sqrt(n+1).to_i do |i|
      if n % i == 0
        n += i
        p = 1
        break
      end
      if p == 0
        n += n
      end
    end
    n += (k-1)*2
  end
  puts n
end

def f(n)
  2.upto(n) { |i| return i if n.modulo(i).zero? }
end

gets.to_i.times do
  n, k = gets.split(' ').map(&:to_i)
  ff = f(n)
  fk = n.div(ff)

  if fk == 1
    n += ff
    ff = 2
    k -= 1
  end

  puts n + ff * k
end


The administration of the Tomsk Region firmly believes that it's time to become a megacity (that is, get population of one million). Instead of improving the demographic situation, they decided to achieve its goal by expanding the boundaries of the city.The city of Tomsk can be represented as point on the plane with coordinates (0; 0). The city is surrounded with n other locations, the i-th one has coordinates (xi, yi) with the population of ki people. You can widen the city boundaries to a circle of radius r. In such case all locations inside the circle and on its border are included into the city.Your goal is to write a program that will determine the minimum radius r, to which is necessary to expand the boundaries of Tomsk, so that it becomes a megacity.

The first line of the input contains two integers n and s (1 ≤ n ≤ 103; 1 ≤ s < 106) — the number of locatons around Tomsk city and the population of the city. Then n lines follow. The i-th line contains three integers — the xi and yi coordinate values of the i-th location and the number ki of people in it (1 ≤ ki < 106). Each coordinate is an integer and doesn't exceed 104 in its absolute value. It is guaranteed that no two locations are at the same point and no location is at point (0; 0).

In the output, print "-1" (without the quotes), if Tomsk won't be able to become a megacity. Otherwise, in the first line print a single real number — the minimum radius of the circle that the city needs to expand to in order to become a megacity. The answer is considered correct if the absolute or relative error don't exceed 10 - 6.

#$stdin.reopen('/home/chen/Desktop/input.txt', 'r')
#$stdout.reopen('/home/chen/Desktop/output.txt', 'w')

=begin
class RQtree

# major method
# :set(ind, value) set array[ind] = value
# :query(i,j) query the minimum number between index i and j
#
	def initialize(array)
		@data = array.clone
		@tree = [0]*1000000
		construct(1, 0,@data.size-1)
	end

	attr_reader :data, :tree
	def min(a,b)
		return a  if a < b
		b
	end

	def construct(ind, i, j)
		if i==j
			@tree[ind] = @data[i]
			return @tree[ind]
		else
			mid = (i+j)/2
			a = construct(2*ind, i, mid)
			b = construct(2*ind+1, mid+1,j)
			@tree[ind] = min(a,b)
			return @tree[ind]
		end
	end

	def inspect(); _inspect(1,0,@data.size-1);end

	def _inspect(ind, b,e)

		puts  "#{b}:#{e} #{@tree[ind]}"
		return if b==e
		_inspect(2*ind, b, (b+e)/2)
		_inspect(2*ind+1, (b+e)/2+1, e)
	end

	def query(i,j); _query(i,j, 1,0, @data.size-1); end

	def _query(i,j,ind, b, e)

		if i>j
			puts 'somethong wrong with index in func _query'
			exit 1
		end

		if i==b and j==e
			return @tree[ind]
		else
			mid = (b+e)/2
			if i>mid
				return _query(i, j, 2*ind+1,  mid+1, e)
			elsif j<= mid
				return _query(i,j,2*ind,b,mid)
			else
				a = _query(i, mid,2*ind,  b, mid)
				b = _query(mid+1,j,2*ind+1, mid+1,e)
				return min(a,b)
			end
		end
	end

	def set(ind, value)
		@data[ind] = value
		update(ind, value)
	end

	def update(ind, value); _update( ind, value,1, 0, @data.size-1);  end

	def _update(ind, value,i,b,e)

		if b==e
			@tree[i] = value
			return
		end
		mid = (b+e)/2
		if ind > mid
			a=_update(ind, value,2*i+1,  mid+1, e)

		else
			_update(ind, value, 2*i, b, mid)
		end
		@tree[i] = min(@tree[2*i], @tree[2*i+1])
	end

end

class Bitree

	def initialize(array)
		@data=array.clone
		@tree= [0]*(array.size+1)
		construct()
	end

	attr_reader :data, :tree
	def construct()
		sum = [0]*(@data.size+1)
		(1..sum.size-1).each do |ind|
			sum[ind] = @data[ind-1]+sum[ind-1]
		end
		@tree[0] = 0
		(1..@tree.size-1).each do |ind|
			i = ind-(ind & -ind)
			@tree[ind] = sum[ind]-sum[i]
		end
	end

	def query(i)
		i+=1
		s=0
		while i>=1
			s+=@tree[i]
			i-= (i&-i)
		end
		s
	end

	def add(i,a)
		@data[i]+=a
		i+=1
		while i<@tree.size
			@tree[i]+=a
			i+=(i&-i)
		end
	end

	def [](i)
		@data[i]
	end
end
=end
=begin
class Graph

	def initialize(g)

		puts 'expected a Array type input' if g.class != Array
		@graph = g
		size = g.size+1
		@visited = [0]*size
		@time = [0] *size
		@father = [-1] *size
		@lev = [-1] * size

	end

	def dfs(); _dfs(-1, [0],0, 1); self;end

	def _dfs(father, time, lev, id)

		@time[id]=time[0]
		@father[id]=father
		@visited[id] = 1
		@lev[id] = lev

		@graph[id].each do |i|
			if @visited[i]!=1
				time[0]+=1
				_dfs(id, time, lev+1 ,i)
			end
		end
	end

	def inspect
		puts "time: #{@time.inspect}"
		puts "father: #{@father.inspect}"
		puts "lev: #{@lev.inspect}"
	end
end

n = gets.to_i
g = [0]*(n+1)

(1..n).each do |i|
	a = gets.split.map(&:to_i)
	g[a[0]] = a[1..(a.size-1)]
end

g = Graph.new(g)

g.dfs.inspect

=end

=begin

n = gets.to_i
m = gets
standing = 0

m.each_char do |c|
	if c == 'X'
		standing += 1
	end
end

if standing == m.size/2
	puts '0'
	puts  m
else

	if standing > m.size/2
		d = standing-m.size/2

		(0..m.size-1).each do |i|
			if m[i] == 'X'
				m[i] = 'x'
				d-=1
				break if d==0
			end
		end
		puts '1'
		puts m
	else
		d = m.size/2-standing
		(0..m.size-1).each do |i|
			if m[i] == 'x'
				m[i] = 'X'
				d-=1
				break if d == 0
			end
		end
		puts '1'
		puts m
	end
end

=end

ncity, p = gets.split.map(&:to_i)

array = []
(1..ncity).each do |i|
	a = gets.split.map(&:to_i)

	array.push(a)
end

array.sort! do |a,b|

	_a = a[0]*a[0]+a[1]*a[1]
	_b = b[0]*b[0]+b[1]*b[1]

	if _a >_b
		1
	else
		-1
	end
end

array.each do |a|

	p+=a[2]
	if p>=1000000
		_a = a[0]*a[0]+a[1]*a[1]
		puts "%.7f" % [Math.sqrt(_a)]
		exit 0
	end
end

puts -1

n,s = gets.split.map(&:to_i)
cities = (1..n).map { |_|
  gets.split.map(&:to_i)
}

ok = false
need = 1000000 - s
min = 0
max = 1000000000
while max - min > 1
  med = (max + min) / 2
  pop = cities.map { |c|
    if c[0] ** 2 + c[1] ** 2 <= med
      c[2]
    else
      0
    end
  }.inject(&:+)
  if need <= pop
    ok = true
    max = med
  else
    min = med
  end
end

if ok
  puts max ** 0.5
else
  puts -1
end


Polycarp got an array of integers $$$a[1 \dots n]$$$ as a gift. Now he wants to perform a certain number of operations (possibly zero) so that all elements of the array become the same (that is, to become $$$a_1=a_2=\dots=a_n$$$). In one operation, he can take some indices in the array and increase the elements of the array at those indices by $$$1$$$.For example, let $$$a=[4,2,1,6,2]$$$. He can perform the following operation: select indices 1, 2, and 4 and increase elements of the array in those indices by $$$1$$$. As a result, in one operation, he can get a new state of the array $$$a=[5,3,1,7,2]$$$.What is the minimum number of operations it can take so that all elements of the array become equal to each other (that is, to become $$$a_1=a_2=\dots=a_n$$$)?

The first line of the input contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$)  — the number of test cases in the test. The following are descriptions of the input test cases. The first line of the description of each test case contains one integer $$$n$$$ ($$$1 \le n \le 50$$$)  — the array $$$a$$$. The second line of the description of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$)  — elements of the array $$$a$$$.

For each test case, print one integer  — the minimum number of operations to make all elements of the array $$$a$$$ equal.

NoteFirst test case:   $$$a=[3,4,2,4,1,2]$$$ take $$$a_3, a_5$$$ and perform an operation plus one on them, as a result we get $$$a=[3,4,3,4,2,2]$$$.  $$$a=[3,4,3,4,2,2]$$$ we take $$$a_1, a_5, a_6$$$ and perform an operation on them plus one, as a result we get $$$a=[4,4,3,4,3,3]$$$.  $$$a=[4,4,3,4,3,3]$$$ we take $$$a_3, a_5, a_6$$$ and perform an operation on them plus one, as a result we get $$$a=[4,4,4,4,4,4]$$$. There are other sequences of $$$3$$$ operations, after the application of which all elements become equal.Second test case:   $$$a=[1000,1002,998]$$$ 2 times we take $$$a_1, a_3$$$ and perform an operation plus one on them, as a result we get $$$a=[1002,1002,1000]$$$.  $$$a=[1002,1002,1000]$$$ also take $$$a_3$$$ 2 times and perform an operation plus one on it, as a result we get $$$a=[1002,1002,1002]$$$. Third test case:   $$$a=[12,11]$$$ take $$$a_2$$$ and perform an operation plus one on it, as a result we get $$$a=[12,12]$$$.

inputs = STDIN.read.strip.split("\n")
inputs.shift

inputs.each_slice(2) do |inp|
    nums = inp[1].split(' ').map(&:to_i)

    max = nums.max
    c = 0
    nums.each_with_index do |num, i|
        c = [c, max - num].max
    end

    puts c
end

n = gets.to_i
max = []
min = []
n.times do |i|
  a = gets.to_i
  a1 = gets.split.map(&:to_i)
  max << a1.max
  min << a1.min
end

n.times do |i|
  puts max[i] - min[i]
end

t = gets.to_i
inputs = []
(0...t).each do
  n = gets.to_i
  arr = gets.chomp
  arr = arr.split(" ").map(&:to_i)
  inputs.push([arr, n])
end

inputs.each do |input|
  max = input[0].max
  min = input[0].min
  puts max-min
end

gets.to_i.times do
  gets
  xs = gets.split.map(&:to_i)
  p xs.max - xs.min
end

t = gets.to_i
while t > 0
  n = gets.to_i
  arr = gets.chomp.split.map(&:to_i).sort
  puts arr[-1] - arr[0]
  t-=1
end

n = gets.chomp.to_i
n.times do |i|
l = gets.chomp.to_i
st = gets.chomp.split
mx = 0
mn = 1000000001
l.times do |element|
    el = st[element].to_i
	if el<mn
	    mn = el
	end
	if el > mx
	    mx = el
	end
end
ans = mx - mn
puts ans
end

t = readline.strip.to_i

t.times do
  readline
  numbers = readline.strip.split(/\s+/).map(&:to_i)

  max = numbers.max
  min = numbers.min

  puts max - min
end

n = gets.to_i
a = gets.to_i
a1 = gets.split.map(&:to_i)
b = gets.to_i
b1 = gets.split.map(&:to_i)
c = gets.to_i
c1 = gets.split.map(&:to_i)

puts a1.max - a1.min
puts b1.max - b1.min
puts c1.max - c1.min


DZY loves chemistry, and he enjoys mixing chemicals.DZY has n chemicals, and m pairs of them will react. He wants to pour these chemicals into a test tube, and he needs to pour them in one by one, in any order. Let's consider the danger of a test tube. Danger of an empty test tube is 1. And every time when DZY pours a chemical, if there are already one or more chemicals in the test tube that can react with it, the danger of the test tube will be multiplied by 2. Otherwise the danger remains as it is.Find the maximum possible danger after pouring all the chemicals one by one in optimal order.

The first line contains two space-separated integers n and m . Each of the next m lines contains two space-separated integers xi and yi (1 ≤ xi < yi ≤ n). These integers mean that the chemical xi will react with the chemical yi. Each pair of chemicals will appear at most once in the input. Consider all the chemicals numbered from 1 to n in some order.

Print a single integer — the maximum possible danger.

NoteIn the first sample, there's only one way to pour, and the danger won't increase.In the second sample, no matter we pour the 1st chemical first, or pour the 2nd chemical first, the answer is always 2.In the third sample, there are four ways to achieve the maximum possible danger: 2-1-3, 2-3-1, 1-2-3 and 3-2-1 (that is the numbers of the chemicals in order of pouring).

n, m = gets.split(' ').map(&:to_i)
ar=(0...n).to_a
def rt(rr,v)
  if ( rr[v]==v )
  elsif ( rr[v]!=rt(rr,rr[v]) )
    rr[v] = rt(rr,rr[v])
  end
  rr[v]
end
(1..m).each do |_|
  x, y = gets.split(' ').map(&:to_i)
  rx = rt(ar,ar[x-1])
  ry = rt(ar,ar[y-1])
  if rx < ry
    ar[ry]=rx
  elsif rx > ry
    ar[rx]=ry
  end
end
(0...n).each do |x|
  rt(ar,x)
end
p 2**(n-(ar.uniq.count))

n,m=gets.split.map(&:to_i)
c=(0..n).to_a
m.times do
  a,b=gets.split.map(&:to_i)
  if c[a]!=c[b]
    x=c[b]
    (n+1).times do |i|
      c[i] = c[a] if c[i] == x
    end
  end
end
p 1<<n-c.uniq.size+1

input = gets.chomp.split
n = Integer(input[0])
m = Integer(input[1])
react = []
for i in 0...m
    react[i] = gets.chomp.split.map{|j| Integer(j)}
end

react_net = []
for i in 0...n
    react_net[i] = []
    for j in 0...n
        react_net[i][j] = false
    end
end

for i in 0...m
    react_net[react[i][0] - 1][react[i][1] - 1] = true
    react_net[react[i][1] - 1][react[i][0] - 1] = true
end
def fill_unit point, unit_id, unit, n, boolean
    if unit[point]
        return
    end

    unit[point] = unit_id
    for i in 0...n
        if boolean[point][i]
            fill_unit(i, unit_id, unit, n, boolean)
        end
    end
end

unit = Array.new(n)
for i in 0...n
    fill_unit(i, i, unit, n, react_net)
end
unit.uniq!
if m == 0
    puts 1
else
    puts 2 ** (n - unit.length)
end

numbers = gets.split(' ')
n = numbers[0].to_i
m = numbers[1].to_i

@graph = Array.new(n + 1) { Array.new }
@seen = Array.new

def dfs(node)
  @seen[node] = true
  nodes = 1
  @graph[node].each do |neighbour|
    if @seen[neighbour].nil?
      nodes += dfs(neighbour)
    end
  end
  nodes
end

m.times do
  pair = gets.split(' ')
  a = pair[0].to_i
  b = pair[1].to_i
  @graph[a].push b
  @graph[b].push a
end

total = 0
n.times do |i|
  if (@seen[i + 1].nil?)
    total += dfs(i + 1) - 1
  end
end

puts 2 ** total

def findf(x, fa)
    if fa[x] != 0
        findf(fa[x], fa)
    else
        x
    end
end
n, m = gets.split.collect{|i| i.to_i}
fa = Array.new(n+1,0)
cnt = Array.new(n+1,1)
m.times do
    x, y = gets.split.collect{|i| i.to_i}
    xx = findf(x, fa)
    yy = findf(y, fa)
    if xx != yy
        fa[yy] = xx
        cnt[xx] += cnt[yy]
    end
end
ans = 0
(1..n).each do |i|
    ans += cnt[i]-1 if fa[i]==0
end
puts 2**ans

def dfs(node)
  return if @vis[node]
  @vis[node] = true
  @n.times do |neighbor|
    dfs(neighbor) if @g[node][neighbor]
  end
end

n, m = gets.split.map(&:to_i)
@vis = Array.new(n)
@n = n
@g = Array.new(n){ Array.new(n) }

m.times do
  i, j = gets.split.map{|s| s.to_i - 1}
  @g[i][j] = @g[j][i] = true
end

ans = 0

n.times do |i|
  if !@vis[i]
    dfs(i)
    ans += 1
  end
end

puts 2 ** (n - ans)

input = $stdin.read.split("\n")
input.shift # get rid of m, n

$graph = {}

# build graph
input.map(&:split).each do |a, b|
  a, b = a.to_i, b.to_i
  $graph[a] ||= []
  $graph[b] ||= []

  $graph[a] << b
  $graph[b] << a
end

$visited = {}
$path = []
$m = 0

def dfs(i)
  return 0 if $visited[i]
  $visited[i] = true
  $graph[i].reduce(1) { |sum, j| sum + dfs(j) }
end

sum = 1

# start from each one to get all disjoint graphs
$graph.keys.each do |key|
  res = dfs(key)
  sum *= 2 ** (res - 1) if res > 0
end

p sum

n, m = gets.split.map(&:to_i)
gr = []
(n+1).times{gr << []}
visited = [-1]*(n+1)
m.times do
  a, b = gets.split.map(&:to_i)
  gr[a] << b
  gr[b] << a
end

q = []

(1..n).each do |v|
  if visited[v] == -1
    visited[v] = 0
    q << v

    while q.size > 0
      gr[q[0]].each do |a|
        if visited[a] == -1
          visited[a] = 1
          q.push(a)
        end
      end
      q.shift
    end

  end
end

puts 2**visited[1..-1].inject{|x, y| x+y}

input = gets.chomp.split
n = Integer(input[0])
m = Integer(input[1])
react = []
for i in 0...m
    react[i] = gets.chomp.split.map{|j| Integer(j)}
end

react_net = []
for i in 0...n
    react_net[i] = []
    for j in 0...n
        react_net[i][j] = false
    end
end

for i in 0...m
    react_net[react[i][0] - 1][react[i][1] - 1] = true
    react_net[react[i][1] - 1][react[i][0] - 1] = true
end
count = 0
for i in 0...n
    for j in 0..i
        if react_net[i][j]
            count += 1
        end
    end
end

if m == 0
    puts 1
else
    puts 2 * count
end

numbers = gets.split(' ')
n = numbers[0].to_i
m = numbers[1].to_i

@graph = Array.new(n + 1) { Array.new }
@seen = Array.new

def dfs(node)
  @seen[node] = true
  @graph[node].each do |neighbour|
    if @seen[neighbour].nil?
      return 1 + dfs(neighbour)
    end
  end
  1
end

m.times do
  pair = gets.split(' ')
  a = pair[0].to_i
  b = pair[1].to_i
  @graph[a].push b
  @graph[b].push a
end

best = 0
n.times do |i|
  if (@seen[i].nil?)
    best = [best, dfs(i) - 1].max
  end
end

puts 2 ** best

numbers = gets.split(' ')
n = numbers[0].to_i
m = numbers[1].to_i

@graph = Array.new(n + 1) { Array.new }
@seen = Array.new
@count = 0

def dfs(node)
  @seen[node] = true
  @count += 1
  @graph[node].each do |neighbour|
    if @seen[neighbour].nil?
      dfs(neighbour)
    end
  end
end

m.times do
  pair = gets.split(' ')
  a = pair[0].to_i
  b = pair[1].to_i
  @graph[a].push b
  @graph[b].push a
end

best = 0
n.times do |i|
  if (@seen[i].nil?)
    @count = 0
    dfs(i)
    best = [best, @count - 1].max
  end
end

puts 2 ** best

n,m=gets.split.map(&:to_i)
c=(0..n).to_a
m.times do
  a,b=gets.split.map(&:to_i)
  if c[a]!=c[b]
    (n+1).times do |i|
      c[i] = c[a] if c[i] == c[b]
    end
  end
end
p c.group_by{|x|x}.values.inject(1){|r,x|r*=1<<(x.size-1)}

n,m=gets.split.map(&:to_i)
c=(0..n).to_a
m.times do
  a,b=gets.split.map(&:to_i)
  if c[a]!=c[b]
    (n+1).times do |i|
      c[i] = c[a] if c[i] == c[b]
    end
  end
end
p 1<<n-c.uniq.size+1


As a big fan of Formula One, Charlie is really happy with the fact that he has to organize ticket sells for the next Grand Prix race in his own city. Unfortunately, the finacial crisis is striking everywhere and all the banknotes left in his country are valued either 10 euros or 20 euros. The price of all tickets for the race is 10 euros, so whenever someone comes to the ticket store only with 20 euro banknote Charlie must have a 10 euro banknote to give them change. Charlie realize that with the huge deficit of banknotes this could be a problem. Charlie has some priceless information but couldn't make use of it, so he needs your help. Exactly n + m people will come to buy a ticket. n of them will have only a single 10 euro banknote, and m of them will have only a single 20 euro banknote. Currently Charlie has k 10 euro banknotes, which he can use for change if needed. All n + m people will come to the ticket store in random order, all orders are equiprobable. Return the probability that the ticket selling process will run smoothly, i.e. Charlie will have change for every person with 20 euro banknote.

The input consist of a single line with three space separated integers, n, m and k (0 ≤ n, m ≤ 105, 0 ≤ k ≤ 10).

Output on a single line the desired probability with at least 4 digits after the decimal point.


A Ministry for Defense sent a general to inspect the Super Secret Military Squad under the command of the Colonel SuperDuper. Having learned the news, the colonel ordered to all n squad soldiers to line up on the parade ground.By the military charter the soldiers should stand in the order of non-increasing of their height. But as there's virtually no time to do that, the soldiers lined up in the arbitrary order. However, the general is rather short-sighted and he thinks that the soldiers lined up correctly if the first soldier in the line has the maximum height and the last soldier has the minimum height. Please note that the way other solders are positioned does not matter, including the case when there are several soldiers whose height is maximum or minimum. Only the heights of the first and the last soldier are important.For example, the general considers the sequence of heights (4, 3, 4, 2, 1, 1) correct and the sequence (4, 3, 1, 2, 2) wrong.Within one second the colonel can swap any two neighboring soldiers. Help him count the minimum time needed to form a line-up which the general will consider correct.

The first input line contains the only integer n (2 ≤ n ≤ 100) which represents the number of soldiers in the line. The second line contains integers a1, a2, ..., an (1 ≤ ai ≤ 100) the values of the soldiers' heights in the order of soldiers' heights' increasing in the order from the beginning of the line to its end. The numbers are space-separated. Numbers a1, a2, ..., an are not necessarily different.

Print the only integer — the minimum number of seconds the colonel will need to form a line-up the general will like.

n = gets.to_i
ar = gets.split(' ').map(&:to_i)
min, max = ar.minmax
maxid, minid = ar.index(max), ar.rindex(min)
r = maxid + n-1 - minid
r -= 1 if maxid > minid
puts r

n=gets.chomp.to_i
i=0
#for i in (0...n)
b=gets.chomp.split(" ").map &:to_i
#end
t1= b.index(b.max)
t2=n-1-b.rindex(b.min)
#puts b.max
#puts t1
#puts b.min
#puts t2
if n>t1+t2
puts t1+t2
else
puts t1+t2-1
end

#end

n = gets.chomp.to_i
na = gets.chomp.split(/ /).map!{|x| x.to_i}

nsa = na.sort
minidx = na.rindex(nsa.first)
maxidx = na.index(nsa.last)
mv = na.length-(minidx+1) + maxidx
mv -= 1 if minidx < maxidx
puts mv

gets
s=gets.split.map &:to_i
n=s.size
z=n-1+s.index(s.max)-s.rindex(s.min)
p n>z ?z:z-1

#!/usr/bin/env ruby
# -*- coding: utf-8 -*-
# Aurhor: seniorihor (12.03.2012)

class General
  def initialize(quantity, numbers)
    @quantity = quantity
    @numbers = numbers
    @seconds = 0
  end
  def calculation_seconds
    if @numbers.rindex(@numbers.min) > @numbers.index(@numbers.max)
      @seconds = @numbers.index(@numbers.max) + @numbers.length - 1 - @numbers.rindex(@numbers.min)
    else
      @seconds = @numbers.index(@numbers.max) + @numbers.length - 2 - @numbers.rindex(@numbers.min)
    end
  end
end
quantity = gets.chomp.to_i
numbers = gets.chomp.split(" ").map! do |i|
  i = i.to_i
end

g = General.new(quantity, numbers)
p g.calculation_seconds

n=gets.to_i;a=gets.split.map(&:to_i);
min=0;max=0;
0.upto(n-1){|i| min=i if a.min==a[i] }
(n-1).downto(0){|i|     max=i if a.max==a[i] }
p max+(n-1-min)-(( min<max )?1:0)

kilkist = gets.chomp.to_i

i=0

soldatu=gets.chomp.split(" ").map! {|el| el=el.to_i}

posMensh=0
posBilsh=0

soldatu.size().times do |j|
  if(soldatu[posBilsh]<soldatu[j])
  posBilsh=j
  end
end

posMensh=kilkist-1
i=posMensh

while(i>=0)
  if(soldatu[posMensh]>soldatu[i])
    posMensh=i
  end
  i-=1
end

sec=0
sec+=posBilsh
sec+=(kilkist-1-posMensh)
sec-=1 if(posBilsh>posMensh)

print sec

#!/usr/bin/env ruby
# -*- coding: utf-8 -*-
# Aurhor: seniorihor  and vertoldo (12.03.2012)

class General
  def initialize(quantity, numbers)
    @quantity = quantity
    @numbers = numbers
    @posMensh=0
    @posBilsh=0
    @sec=0
  end

  def calculation_seconds

    @numbers.size().times do |j|
      if(@numbers[@posBilsh]<@numbers[j])
       @posBilsh=j
      end
    end

    @posMensh=@quantity-1
    i=@posMensh

    while(i>=0)
      if(@numbers[@posMensh]>@numbers[i])
        @posMensh=i
      end
      i-=1
    end

    @sec+=@posBilsh
    @sec+=(@quantity-1-@posMensh)
    @sec-=1 if(@posBilsh>@posMensh)

    return @sec
  end
end

quantity = gets.chomp.to_i
numbers = gets.chomp.split(" ").map! {|el| el=el.to_i}
g = General.new(quantity, numbers)
print g.calculation_seconds

n = gets.to_i
a = gets.split.map(&:to_i)

min, max = 0, 0
a.each_index do |i|
  min = i if a[min] >= a[i]
  max = i if a[max] < a[i]
end
cnt = max + (a.size - 1 - min)
cnt -= 1 if max > min
puts  cnt

def order(n,a)
  minmax = a.minmax
  min = minmax.shift
  max = minmax.shift

  #As the smaller soldier has to be at the end of the line we need to look for the closest one to that pos
  min_pos = a.rindex(min)
  # The highest soldier has to be first that's why we start looking from the beginig of the line
  max_pos = a.index(max)

  tot_sec = 0
  #Checking if the soldiers have to be swapped between them
  if min_pos < max_pos
    # Has to be -2 because of the array index and one less to the end of line,
    # that's because the soldiers are swapped between them and we consider that time on the max_pos
    tot_sec = max_pos + ((n-2) - min_pos)
  else
    tot_sec = max_pos + ((n-1) - min_pos)
  end

  tot_sec
end

n = gets.to_i
a = gets.split(/\s/).map(&:to_i)
puts order(n,a)

n = $stdin.gets.to_i
milita = $stdin.gets.split.map { |x| x.to_i }

max = 0
maxidx = -1

n.times do |i|
  if max < milita[i]
    max = milita[i]
    maxidx = i
  end
end

result = maxidx

maxidx.downto(1) do |i|
  t = milita[i]
  milita[i] = milita[i-1]
  milita[i-1] = t
end

min = 10000000
minidx = -1

n.times do |k|
  i = n - k - 1

  if min > milita[i]
    min = milita[i]
    minidx = i
  end
end

result += n - 1 - minidx

p result

n=gets.chomp.to_i
a=gets.chomp.split.map(&:to_i)
mn=a.min
mx=a.max
mn_pos = a.rindex(mn)
ans=0
for i in mn_pos...a.size-1
	a[i],a[i+1]=a[i+1],a[i]
	ans+=1
end
mx_pos=a.index(mx)
for i in 1..mx_pos
	a[i],a[i+1]=a[i+1],a[i]
	ans+=1
end
puts ans

gets
a = gets.strip.split.map(&:to_i).to_a
p a.size - a.rindex(a.min) - 1 + a.index(a.max) - (a.index(a.max) > a.rindex(a.min) ? 1 : 0)

n = gets.to_i

a = gets.chomp.split(' ').map &:to_i

l = a.index(a.max)
r = a.rindex(a.min)
if l > r
  puts a.size-2 +l - r
else
  puts a.size-1 + l -r
end

n=gets.to_i
a=gets.split.map(&:to_i)
max_index=a.index(a.max)
min_index=a.rindex(a.min)
p max_index<min_index ? max_index+(n-min_index-1) : max_index+(n-min_index-2)

n = $stdin.readline.to_i
a = $stdin.readline.split.map(&:to_i)

max = a.max
min = a.min

maxi = a.find_index(max)

k = 0
i = maxi
while i>0
    a[i-1], a[i] = a[i], a[i-1]
    i-=1
    k+=1
end

mini = a.count - a.reverse.find_index(min) - 1
i = mini
while i<a.count-1
    a[i+1], a[i] = a[i], a[i+1]
    i+=1
    k+=1
end

puts k

#!/usr/bin/ruby
def read_int; gets.chomp.to_i; end
def read_ints; gets.chomp.split.map(&:to_i); end
def read_chars; gets.chomp.split(''); end

read_int
arr = read_ints

min_index = arr.rindex(arr.min)
max_index = arr.index(arr.max)
n = max_index + arr.size - 1 - min_index
n -= 1 if min_index < max_index

puts n

gets
arr = gets.split.map &:to_i
max_ind = arr.index(arr.max)
min_ind = (arr.reverse.index(arr.min) - arr.size + 1).abs
if max_ind > min_ind
  puts max_ind + arr.size - min_ind - 2
else
  puts max_ind + arr.size - min_ind - 1
end

s=gets()
n=s.to_i
s=gets()
s=s.chop()
at=0

a=Array.new(n)
for i in (0..n-1) do
	cur=0
	while (at<s.length and s[at]!=' ')
		cur=cur*10+s[at].to_i
		at+=1
	end
	at+=1
	a[i]=cur
end
min=n-1
max=0
for i in (0..n-1) do
if(a[i]>a[max])
max=i
end
if(a[n-1-i]<a[min])
min=n-1-i
end
end
res=0
res=max+n-1-min
if(min<max)
res-=1
end
puts res

n = gets.chomp.to_i
arr = Array.new(n)
arr = gets.split.map &:to_i
big = [0,0]
small = [1000,0]
n.times do |i|
  if arr[i] > big[0]
    big[0] = arr[i]
    big[1] = i
  end

  if arr[i] <= small[0]
    small[0] = arr[i]
    small[1] = i
  end

end

flag = 0
if big[1] > small[1]
  flag = 1
end

puts (big[1] - 0) + ((n-1) - small[1]) - flag

n = gets.to_i
as = gets.split.map(&:to_i)

min_index = as.rindex(as.min)
max_index = as.index(as.max)

puts (n - min_index - 1) + max_index - (min_index < max_index ? 1 : 0)

gets
s=gets.split.map &:to_i
n=s.size
z=n-1+s.index(s.max)-s.rindex(s.min)
p n>z ?z:z-1

gets.chomp.to_i
line = gets.chomp.split(/ /).map(&:to_i)
len = line.length - 1
min_height = line.min
max_height = line.max
min_pos = line.rindex min_height
max_pos = line.index max_height
delta = 0
delta = 1 if min_pos < max_pos
puts (max_pos - 0) + (len - min_pos) - delta

n=gets.to_i
x=gets.split.map{|e| e.to_i}
min1=x[0]
max1=x[0]
minP=0
maxP=0
n.times{|i|
	if x[i]<=min1 then
		min1=x[i]
		minP=i
	end
}
n.times{|i|
	if max1<x[i] then
		max1=x[i]
		maxP=i
	end
}
ans=0
if minP<maxP then
	ans=-1
end
puts ans+(n-1-minP)+(maxP)

n = gets.to_i
a = gets.split.map(&:to_i)

max = a.sort[-1]
min = a.sort[0]

imx = a.index(max)
imn = a.rindex(min)

if imx > imn
  p imx + (n-imn-1) - 1
else
  p imx + (n-imn-1)
end

n = gets.chomp.to_i
arr = gets.chomp.split.map(&:to_i)

max_ind = arr.find_index(arr.max)
min_ind = arr.rindex(arr.min)
# p max_ind, min_ind
if max_ind > min_ind
  puts (max_ind) + ((n-1) - min_ind) - 1
else
  puts (max_ind) + ((n-1) - min_ind)
end

#=================================
# Better be sure than sorry.
#=================================
$stdin=File.open("./input.txt","r") if ENV["LOGNAME"]=="skydos"
require 'prime'
#require 'mathn'
require 'matrix'
require 'set'
include Math
#=================================

n=gets.to_i
data=gets.split.map(&:to_i)

mini=data.min
maxy=data.max

mini_pos = data.rindex(mini)
ans=0
for i in mini_pos...data.size-1
	tmp=data[i]
	data[i]=data[i+1]
	data[i+1]=tmp
	ans+=1
end

maxy_pos=data.index(maxy)
for i in 1..maxy_pos
	tmp=data[i]
	data[i]=data[i+1]
	data[i+1]=tmp
	ans+=1
end

puts ans

numSol = gets.to_i
a = gets.split.map {|x| x.to_i}

leftMax = 0
rightMin = numSol-1

for x in 0...numSol
	y = numSol-1-x
	leftMax = x if a[x]>a[leftMax]
	rightMin = y if a[y]<a[rightMin]
end

ans = leftMax+(numSol-rightMin-1)

ans -= 1 if leftMax>rightMin

puts ans

n=gets.to_i
a=gets.split
a.collect! {|i| i.to_i}

for i in 1..n
	if a[-i] == a.max then l=n-i end
	if a[i-1] == a.min then r=n-i end
end

puts (if l+r>=n then l+r-1 else l+r end)

n=gets.to_i
a=gets.split.collect! {|i| i.to_i}
for i in 1..n
	if a[-i] == a.max then l=n-i end
	if a[i-1] == a.min then r=n-i end
end
puts (if l+r>=n then l+r-1 else l+r end)

i = gets.to_i

array = gets.chomp.split.map(&:to_i)

min_index = array.rindex(array.min)
max_index = array.index(array.max)

length = array.length - 1

if max_index < min_index
  swaps = (length-min_index) + max_index
else
  swaps = (length-min_index) + max_index - 1
end

puts swaps

n = gets.to_i
a = gets.split.map(&:to_i)

ans = 0
maxv = a.max
minv = a.min

i = a.index(maxv)
ans += i
a.delete_at(i)
a.unshift(maxv)

i = a.rindex(minv)
ans += a.size - i - 1

puts ans

gets
s = gets.split(' ').map(&:to_i)
sorted = s.sort
min = sorted.first
max = sorted.last
max_index = s.find_index(max)
min_index = s.reverse.find_index(min)
result = s.find_index(max) + s.reverse.find_index(min)
result -= 1 if max_index > s.size - min_index - 1
puts result

n = Integer(gets.chomp)
h = gets.chomp.split
height = Array.new
for i in 0...n
    height[i] = Integer(h[i])
end

max = 0
min = 101
for i in 0...n
    if height[i] > max
        max = height[i]
    end
end
for i in 0...n
    if height[i] < min
        min = height[i]
    end
end

max_index = Array.new
min_index = Array.new
for i in 0...n
    if height[i] == max
        max_index.push(i)
    elsif height[i] == min
        min_index.push(i)
    end
end

x = min_index.length
if max == min
    puts 0
elsif max_index[0] > min_index[x-1]
    puts max_index[0] + n - 2 - min_index[x-1]
else
    puts max_index[0] + n - 1 - min_index[x-1]
end

n = gets.chomp.to_i
a = gets.chomp.split.map(&:to_i)

min, max = a.minmax

wmax = a.index(max)
wmin = a.rindex(min)

ans = wmax + a.size - wmin - 1
ans -= 1 if wmax > wmin

puts ans

n = gets.to_i
arr = gets.split(" ").map(&:to_i)
arr.reverse!

min,min_index = arr.each_with_index.min

arr.unshift(arr.delete_at(min_index))
secs = min_index

max,max_index = arr.each_with_index.max
secs += (n - max_index - 1)
puts secs

number_of_soldiers = gets.to_i
soldiers = gets.split.map &:to_i

shortest = number_of_soldiers - 1 - soldiers.reverse.index(soldiers.min)
tallest = soldiers.index(soldiers.max)
puts tallest + number_of_soldiers - shortest - (tallest > shortest ? 1 : 0) - 1

ar = []
n = gets.to_i
ar = gets.split.map &:to_i
#puts ar.index(ar.max)
x = ar.index(ar.max)
y = ar.rindex(ar.min)
a = x
b = n-y-1
puts y < x ? a + b-1 : a + b

gets
s=gets.split.map &:to_i
n=s.size
z=n-1+s.index(s.max)-s.rindex(s.min)
p n>z ?z:z-1

gets
l = gets.split.map(&:to_i)
m = l.index(l.max)
l.delete_at(m)
puts m + l.reverse.index(l.min)

n=gets.to_i; d=gets.split.map(&:to_i); sum=d.index(d.max); d[d.index(d.max)]+=1;
p d.index(d.max) + (d.select{|x| x!=d.max}.reverse.push(d.max).index(d.min))

n = gets.to_i
a = gets.split.map(&:to_i)
mii = a.rindex(a.min)
mxi = a.index(a.max)
ans = mxi + (n - 1 - mii)
ans -= 1 if mxi > mii
puts ans

n = gets.to_i
a = gets.split.map(&:to_i)
mi = a.min
mx = a.max
mii = a.rindex(mi)
mxi = a.index(mx)
ans = mxi + (n - 1 - mii)
ans -= 1 if mxi > mii
puts ans

n = gets.to_i
a = gets.split.map(&:to_i)
mi = a.min
mx = a.max
mii = 0
mxi = 0
for i in 0...n
  if a[i] == mi
    mii = i
    mi = a[i]
  end
end
for i in 0...n
  if a[i] == mx
    mxi = i
    mx = a[i]
    break;
  end
end
ans = mxi + (n - 1 - mii)
ans -= 1 if mxi > mii
puts ans

def swap (i, d)
  tmp = $a[i]
  $a[i] = $a[i + d]
  $a[i + d] = tmp
  i + d
end
n = gets.to_i
$a = gets.split.map(&:to_i)
mi = $a.min
mx = $a.max
ans = 0
mii = 0
mxi = 0
n.times do |i|
  if $a[i] == mx
    mxi = i
    break
  end
end
while mxi != 0
  mxi = swap(mxi, -1)
  ans += 1
end
n.times do |i|
  mii = i if $a[i] == mi
end
while mii != n - 1
  mii = swap(mii, 1)
  ans += 1
end
puts ans

n = gets.chomp.to_i

array = gets.chomp.split(" ")

maxi = 0
mini = 105

id = 0

for i in 0...n
	a = array[i].to_i

	if a<=mini
		mini = a
		id = i;
	end

	i += 1
end

cont = 0

while id<n-1 do

	a = array[id]
	array[id] = array[id+1]
	array[id + 1] = a

	id += 1
	cont += 1

end

j = n - 1

while j>=0 do
	a = array[j].to_i

	if a>=maxi
		maxi = a
		id = j;
	end

	j -= 1
end

while id>=1 do

	a = array[id]
	array[id] = array[id-1]
	array[id - 1] = a

	id -= 1
	cont += 1

end

puts cont

n=gets.to_i

a=[]
(n-1).times {
a.push gets(' ').to_i
}
a.push gets.to_i

mi=a.min
ma=a.max

for i in 0..a.size-1
if a[i]==ma
ma_i=i
break
end
end

i=a.size-1
while i>=0
if a[i]==mi
mi_i=i
break
end

i-=1
end

ret=ma_i+n-mi_i-1
if ma_i>mi_i
ret-=1
end

p ret

length = gets.chomp.to_i
heights = gets.chomp.split()
min, max = heights.minmax_by {|h| h.to_i}
minindex = heights.rindex(min)
maxindex = heights.index(max)
if maxindex < minindex
        print maxindex + heights.length - minindex - 1
else
        print maxindex - minindex + minindex + heights.length - minindex - 1 - 1
end

gets
a = gets.split(' ').map(&:to_i)

imax = a.index(a.max)
imin = a.size - a.rindex(a.min) -1

puts imax + imin - (imax > a.size - imin - 1 ? 1 : 0)

max = [0, 0]
min = [101, 0]
n = Integer(gets.chomp)
gets.chomp.split.each_with_index { |s, i|
  h = s.to_i
  if h > max[0]
    max = [h, i]
  end
  if h <= min[0]
    min = [h, i]
  end
}
puts max[1] + (n - min[1] - 1) - (max[1] > min[1] ? 1 : 0)

n = gets.to_i
a = gets.split.map(&:to_i)
a.delete_at(ans = a.find_index(a.max))
a.reverse!
ans += a.find_index(a.min)
p ans

STDIN.gets
i = STDIN.gets.split(' ').map(&:to_i)

max, min = i.max, i.min

max_i = -1; min_i = 100

i.length.times do |k|
	max_i = k if max_i == -1 and i[k] == max
	min_i = k if i[k] == min
end

c = max_i - 1 + i.length - min_i
c -= 1 if max_i > min_i

STDOUT.puts c

#!ruby

n = gets.to_i

data = gets.split.map{|e|e.to_i}

max_num = data.max
min_num = data.min
max_index = data.index(max_num)
min_index = data.rindex(min_num)

puts max_index + data.length - min_index  -1+ (max_index>min_index ? -1 :  0 )

n=gets.chomp.to_i
i=0
#for i in (0...n)
b=gets.chomp.split(" ").map &:to_i
#end
t1= b.index(b.max)
t2=n-1-b.index(b.min)
puts b.max
puts t1
puts b.min
puts t2
if n>t1+t2
puts t1+t2
else
puts t1+t2-1
end

#end

n=gets.chomp.to_i
i=0
#for i in (0...n)
b=gets.chomp.split(" ").map &:to_i
#end
t1= b.index(b.max)
t2=n-1-b.index(b.min)
#puts b.max
#puts t1
#puts b.min
#puts t2
if n>t1+t2
puts t1+t2
else
puts t1+t2-1
end

#end

n=gets.chomp.to_i
i=0
#for i in (0...n)
b=gets.chomp.split(" ")
#end
t1= b.index(b.max)
t2=n-b.rindex(b.min)-1
if n>t1+t2
puts t1+t2
else
puts t1+t2-1
end

kilkist = gets.chomp.to_i

soldatu=gets.chomp.split(" ").map! {|el| el=el.to_i}

posMensh=soldatu.rindex(soldatu.min)

posBilsh=soldatu.rindex(soldatu.max)

sec=0

if(posMensh!=posBilsh)

  sec+=posBilsh

  sec+=(kilkist-1-posMensh)

  sec-=1 if(posBilsh>posMensh)

end

print sec

n = $stdin.readline.to_i
a = $stdin.readline.split.map(&:to_i)

max = a.max
min = a.min

maxi = a.find_index(max)
mini = a.reverse.find_index(min)

if maxi!=mini
    k = maxi+mini-1
else
    k = maxi+mini
end

puts k

n = $stdin.readline.to_i
a = $stdin.readline.split.map(&:to_i)

max = a.max
min = a.min

if a.count == 2
    if a.first == max && a.last == min
        puts 0
    else
        puts 1
    end
else

    maxi = a.find_index(max)
    mini = a.reverse.find_index(min)

    if maxi!=mini
        k = maxi+mini-1
    else
        k = maxi+mini
    end

    puts k
end

gets
h = gets.split.map &:to_i
numb = h.index(h.max) + h.size - (h.reverse.index(h.min) - h.size).abs
numb -= 1 if h.index(h.max) > h.index(h.min)
puts numb

gets
h = gets.split.map &:to_i
numb = h.index(h.max) + h.size - (h.reverse.index(h.min) - h.size).abs
numb -= 1 if h.index(h.max) > (h.reverse.index(h.min) - h.size).abs
puts numb

n = gets.chomp.to_i
arr = gets.chomp.split.map(&:to_i)

max_ind = arr.rindex(arr.max)
min_ind = arr.rindex(arr.min)
# p max_ind, min_ind
if max_ind > min_ind
  puts (max_ind) + ((n-1) - min_ind) - 1
else
  puts (max_ind) + ((n-1) - min_ind)
end

ar = []
n = gets.to_i
ar = gets.split.map &:to_i
#puts ar.index(ar.max)
x = ar.index(ar.max)
y = n-ar.rindex(ar.min)-1
puts y < x ? x+y-1 : x+y

gets
l = gets.split.map(&:to_i)
m = l.index(l.max)
l.delete(l.max)
puts m + l.reverse.index(l.min)

gets
l = gets.split.map(&:to_i)
m = l.index(l.max)
l.delete(m)
puts m + l.reverse.index(l.min)

gets
l = gets.split.map(&:to_i)
m = l.each_with_index.max
l.delete(m[0])
puts m[1] + l.reverse.each_with_index.min[1]

gets
l = gets.split.map(&:to_i)
m = l.index(l.max)
l.delete(m)
puts m + l.reverse.each_with_index.min[1]

n=gets.to_i; d=gets.split.map(&:to_i); sum=d.index(d.max);
p d.index(d.max) + (d.reverse.select{|x| x!=d.max}.push(d.max).index(d.min))

n=gets.to_i

a=[]
(n-1).times {
a.push gets(' ').to_i
}
a.push gets.to_i

mi=a.min
ma=a.max

for i in 0..a.size-1
if a[i]==ma
ma_i=i
break
end
end

i=a.size-1
while i>=0
if a[i]==mi
mi_i=i
break
end

i-=1
end

ret=ma_i+n-mi_i
if ma_i>mi_i
ret-=1
end

p ret

gets
a = gets.split(' ').map(&:to_i)

imax = a.index(a.max)
imin = a.rindex(a.min)

puts imax + (a.size - imin - 1) - (imax > a.index(a.min) ? 1 : 0)

gets
a = gets.split(' ').map(&:to_i)

imax = a.index(a.max)
imin = a.size - a.rindex(a.min) -1

puts imax + imin - (imax > a.size - imin ? 1 : 0)

gets
a = gets.split(' ').map(&:to_i)

imax = a.index(a.max)
imin = a.size - a.rindex(a.min) -1

p imax, imin

puts imax + imin - (imax > a.size - imin ? 1 : 0)

STDIN.gets
i = STDIN.gets.split(' ').map(&:to_i)

max, min = i.max, i.min

if max == i.first and min = i.last
    STDOUT.puts 0
    exit
end

max_i = 0; min_i = 101

i.length.times do |k|
    max_i = k if max_i == 0 and i[k] == max
    min_i = k if i[k] == min
end

c = max_i - 1 + i.length - min_i
c -= 1 if max_i > min_i

STDOUT.puts c

STDIN.gets
i = STDIN.gets.split(' ').map(&:to_i)

max, min = i.max, i.min
max_i = 0; min_i = 101

i.length.times do |k|
	max_i = k if max_i == 0 and i[k] == max
	min_i = k if i[k] == min
end

c = max_i - 1 + i.length - min_i
c -= 1 if max_i > min_i

STDOUT.puts c

STDIN.gets
i = STDIN.gets.split(' ').map(&:to_i)

max, min = i.max, i.min

if max == i.first and min == i.last
	STDOUT.puts 0
	exit
end

max_i = 0; min_i = 101

i.length.times do |k|
	max_i = k if max_i == 0 and i[k] == max
	min_i = k if i[k] == min
end

c = max_i - 1 + i.length - min_i
c -= 1 if max_i > min_i

STDOUT.puts c

#!ruby

n = gets.to_i

data = gets.split.map{|e|e.to_i}

max_num = data.max
min_num = data.min
max_index = data.index(max_num)
min_index = data.length - data.rindex(min_num) -1

puts max_index + min_index + (max_index>min_index ? -1 :  0 )


There are n student groups at the university. During the study day, each group can take no more than 7 classes. Seven time slots numbered from 1 to 7 are allocated for the classes.The schedule on Monday is known for each group, i. e. time slots when group will have classes are known.Your task is to determine the minimum number of rooms needed to hold classes for all groups on Monday. Note that one room can hold at most one group class in a single time slot.

The first line contains a single integer n (1 ≤ n ≤ 1000) — the number of groups.  Each of the following n lines contains a sequence consisting of 7 zeroes and ones — the schedule of classes on Monday for a group. If the symbol in a position equals to 1 then the group has class in the corresponding time slot. In the other case, the group has no class in the corresponding time slot.

Print minimum number of rooms needed to hold all groups classes on Monday.

NoteIn the first example one room is enough. It will be occupied in each of the seven time slot by the first group or by the second group.In the second example three rooms is enough, because in the seventh time slot all three groups have classes.


You are given a huge decimal number consisting of $$$n$$$ digits. It is guaranteed that this number has no leading zeros. Each digit of this number is either 0 or 1.You may perform several (possibly zero) operations with this number. During each operation you are allowed to change any digit of your number; you may change 0 to 1 or 1 to 0. It is possible that after some operation you can obtain a number with leading zeroes, but it does not matter for this problem.You are also given two integers $$$0 \le y < x < n$$$. Your task is to calculate the minimum number of operations you should perform to obtain the number that has remainder $$$10^y$$$ modulo $$$10^x$$$. In other words, the obtained number should have remainder $$$10^y$$$ when divided by $$$10^x$$$.

The first line of the input contains three integers $$$n, x, y$$$ ($$$0 \le y < x < n \le 2 \cdot 10^5$$$) — the length of the number and the integers $$$x$$$ and $$$y$$$, respectively. The second line of the input contains one decimal number consisting of $$$n$$$ digits, each digit of this number is either 0 or 1. It is guaranteed that the first digit of the number is 1.

Print one integer — the minimum number of operations you should perform to obtain the number having remainder $$$10^y$$$ modulo $$$10^x$$$. In other words, the obtained number should have remainder $$$10^y$$$ when divided by $$$10^x$$$.

NoteIn the first example the number will be $$$11010100100$$$ after performing one operation. It has remainder $$$100$$$ modulo $$$100000$$$.In the second example the number will be $$$11010100010$$$ after performing three operations. It has remainder $$$10$$$ modulo $$$100000$$$.

n, x, y = gets.split.map(&:to_i)
s = gets.chomp.reverse
goal = '0' * x
goal[y] = '1'
puts s[0, x].chars.zip(goal.chars).count { _1 != _2 }

#!usr/bin/env ruby

# https://codeforces.com/problemset/problem/1165/A

input = gets.split(' ').map(&:to_i)
num = gets.chomp

n = input[0]
x = input[1]
y = input[2]

counter = 0

(0..x-1).each do |i|
 if i == y
  counter += 1 if num[n-i-1] == '0'
 elsif num[n-i-1] == '1'
  counter += 1
 end
end

puts counter

if File.exists?("input")
  $stdin = File.open("input")
  $stdout = File.open("output","w")
end

nxy = gets.chomp.split(" ").map(&:to_i)
n = nxy[0]
x = nxy[1]
y = nxy[2]

s = gets.chomp

ans=0
(0..x-1).each do |i|
#	p i
#	p s[s.length-i-1]
	if(i==y)
		if(s[s.length-i-1]=='0')
			ans+=1
		end
	else
#		p i
		if(s[s.length-i-1]=='1')
			ans+=1
		end
	end
end

puts ans


One day Ms Swan bought an orange in a shop. The orange consisted of n·k segments, numbered with integers from 1 to n·k. There were k children waiting for Ms Swan at home. The children have recently learned about the orange and they decided to divide it between them. For that each child took a piece of paper and wrote the number of the segment that he would like to get: the i-th (1 ≤ i ≤ k) child wrote the number ai (1 ≤ ai ≤ n·k). All numbers ai accidentally turned out to be different.Now the children wonder, how to divide the orange so as to meet these conditions:  each child gets exactly n orange segments;  the i-th child gets the segment with number ai for sure;  no segment goes to two children simultaneously. Help the children, divide the orange and fulfill the requirements, described above.

The first line contains two integers n, k (1 ≤ n, k ≤ 30). The second line contains k space-separated integers a1, a2, ..., ak (1 ≤ ai ≤ n·k), where ai is the number of the orange segment that the i-th child would like to get. It is guaranteed that all numbers ai are distinct.

Print exactly n·k distinct integers. The first n integers represent the indexes of the segments the first child will get, the second n integers represent the indexes of the segments the second child will get, and so on. Separate the printed numbers with whitespaces. You can print a child's segment indexes in any order. It is guaranteed that the answer always exists. If there are multiple correct answers, print any of them.

nk = gets.split
wishes = gets.split
n = nk[0].to_i
k = nk[1].to_i
a = Array.new(n*k){|i| i+= 1}
res = []
i = 0
while i<k do
    wishes[i] = wishes[i].to_i
    res[i] = [wishes[i]]
    i += 1
end
a = a - wishes
i = 0
while i<k do
    c = a[0...n-1]
    res[i] += c
    a = a - c
    res[i] = res[i].sort
    j = 0
    while j<n do
        print "#{res[i][j]} "
        j += 1
    end
    print "\n"
    i += 1
end

n,k=gets.split.map(&:to_i)
a=gets.split.map(&:to_i)
an=Array.new
a.each{|e| an<<[e]}
b=(1..(n*k)).to_a-a
for i in 0...k
	(n-1).times{an[i]<<b[0];b.delete_at(0)}
end
an.each{|e| puts e.join(" ")}

n, k = gets.chomp.split(" ").map{|e| e.to_i}
a = gets.chomp.split(" ").map{|e| e.to_i}
numbers = []
for i in 1 .. n * k do
  numbers << i
end
ans = []
k.times do
  ans << []
end

a.each_with_index do |num, idx|
  ans[idx] << num
  numbers.delete num
end

numbers.each_with_index do |num, idx|
  ans[idx % k] << num
end

ans.each do |line|
  puts line.join(" ")
end

n, k = gets.split.map(&:to_i)
a = gets.split.map(&:to_i)
d = (1..n*k).to_a
r = []
k.times do |i|
  t = []
  t.push a[i]
  r.push t
  d -= [a[i]]
end
k.times do |i|
  (n-1).times do
    r[i].push d[0]
    d.shift
  end
end
r.each do |x|
  puts x*' '
end

a=gets.chomp.split(" ")
0.upto(1) {|i| a[i]=a[i].to_i    }
b=gets.chomp.split(" ")
0.upto(a[1]-1) {|i| b[i]=b[i].to_i    }
c=(1.. (a[0] * a[1])).to_a
1.upto(a[1]) do |i|
ind=c.index(b[i-1])
swp=c[i*a[0]-1]
c[i*a[0]-1]=b[i-1]
c[ind]=swp
end

i=0
(a[1]).times do
a[0].times do
printf "#{c[i]} "
i+=1
end
puts ""
end

n,k=gets.split.map(&:to_i)
a=gets.split.map(&:to_i)

o=1

k.times{|i|
  print a[i].to_s+' '
  (n-1).times{
    o+=1 while a.include? o
    print o.to_s+' '
    o+=1
  }
  puts
}

n, k = gets.split.map &:to_i
a = gets.split.map &:to_i
ar = Array.new(n*k) { |i| 1 if a.include?(i) }

pointer = 1
a.each do |element|
  print "%d " % element
  counter = n-1
  while counter > 0 do
     if ar[pointer].nil?
       print "%d " % pointer
       counter -= 1
       ar[pointer] = 1
     end
    pointer += 1
  end
  print "\n"
end

def read_next_line
  gets.chomp.split.map { |x| x.to_i }
end

n, k = read_next_line
a = read_next_line
g = []
for i in 0...a.size
  g << [a[i]]
end
if n > 1
  i, j = 0, 1
  for x in 1..k * n
    unless a.include? x
      g[i] << x
      j += 1
      if j == n
        j = 1
        i += 1
      end
    end
  end
end
g.each { |z| puts z * ' ' }

t = gets.split.collect{|x| x.to_i}
n,k = t[0], t[1]

a = gets.split.collect{|x| x.to_i}
answer = []

a.each do |c|
	print c,' '
	m = 1
	for i in 1..n*k
		if m == n
			break
		end
		if not a.include?(i) and not answer.include?(i)
			answer << i
			m+=1
			print i,' '
		end
	end
	puts
end

n,k=gets.split.map(&:to_i)
a=gets.split.map(&:to_i)
b=(1..(n*k)).to_a-a
for i in 0...k do
	print a[i]," ",b[0...n-1].join(" ")
	print "\n"
end