You are given a grid with $$$n$$$ rows and $$$m$$$ columns, where each cell has a non-negative integer written on it. We say the grid is good if for each cell the following condition holds: if it has a number $$$k > 0$$$ written on it, then exactly $$$k$$$ of its neighboring cells have a number greater than $$$0$$$ written on them. Note that if the number in the cell is $$$0$$$, there is no such restriction on neighboring cells.You are allowed to take any number in the grid and increase it by $$$1$$$. You may apply this operation as many times as you want, to any numbers you want. Perform some operations (possibly zero) to make the grid good, or say that it is impossible. If there are multiple possible answers, you may find any of them.Two cells are considered to be neighboring if they have a common edge.

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \le t \le 5000$$$)  — the number of test cases. The description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \le n, m \le 300$$$)  — the number of rows and columns, respectively. The following $$$n$$$ lines contain $$$m$$$ integers each, the $$$j$$$-th element in the $$$i$$$-th line $$$a_{i, j}$$$ is the number written in the $$$j$$$-th cell of the $$$i$$$-th row ($$$0 \le a_{i, j} \le 10^9$$$). It is guaranteed that the sum of $$$n \cdot m$$$ over all test cases does not exceed $$$10^5$$$.

If it is impossible to obtain a good grid, print a single line containing "NO". Otherwise, print a single line containing "YES", followed by $$$n$$$ lines each containing $$$m$$$ integers, which describe the final state of the grid. This final grid should be obtainable from the initial one by applying some operations (possibly zero). If there are multiple possible answers, you may print any of them.

NoteIn the first test case, we can obtain the resulting grid by increasing the number in row $$$2$$$, column $$$3$$$ once. Both of the cells that contain $$$1$$$ have exactly one neighbor that is greater than zero, so the grid is good. Many other solutions exist, such as the grid $$$$$$0\;1\;0\;0$$$$$$ $$$$$$0\;2\;1\;0$$$$$$ $$$$$$0\;0\;0\;0$$$$$$ All of them are accepted as valid answers.In the second test case, it is impossible to make the grid good.In the third test case, notice that no cell has a number greater than zero on it, so the grid is automatically good.

def get_edge(ri, ci, rows, columns)
    e = if ri > 0
        1
    else
        0
    end
    e += if ri < rows - 1
        1
    else
        0
    end
    e += if ci > 0
        1
    else
        0
    end
    e += if ci < columns - 1
        1
    else
        0
    end
    e
end

tests = gets.strip.to_i

tests.times{|t|
    row, column = gets.strip.split(' ').map(&:to_i)
    can_solve = true
    field = row.times.map{|r|
        gets.strip.split(' ').each_with_index.map{|c, n|
            break unless can_solve
            edge_num = get_edge(r, n, row, column)
            if c.to_i > edge_num
                can_solve = false
                break
            end
            edge_num
        }
    }
    if can_solve
        puts 'YES'
        field.each{|row| puts row.join(' ') }
    else
        puts 'NO'
    end
}


Nian is a monster which lives deep in the oceans. Once a year, it shows up on the land, devouring livestock and even people. In order to keep the monster away, people fill their villages with red colour, light, and cracking noise, all of which frighten the monster out of coming.Little Tommy has n lanterns and Big Banban has m lanterns. Tommy's lanterns have brightness a1, a2, ..., an, and Banban's have brightness b1, b2, ..., bm respectively.Tommy intends to hide one of his lanterns, then Banban picks one of Tommy's non-hidden lanterns and one of his own lanterns to form a pair. The pair's brightness will be the product of the brightness of two lanterns.Tommy wants to make the product as small as possible, while Banban tries to make it as large as possible.You are asked to find the brightness of the chosen pair if both of them choose optimally.

The first line contains two space-separated integers n and m (2 ≤ n, m ≤ 50). The second line contains n space-separated integers a1, a2, ..., an. The third line contains m space-separated integers b1, b2, ..., bm. All the integers range from  - 109 to 109.

Print a single integer — the brightness of the chosen pair.

NoteIn the first example, Tommy will hide 20 and Banban will choose 18 from Tommy and 14 from himself.In the second example, Tommy will hide 3 and Banban will choose 2 from Tommy and 1 from himself.

n,m=gets.split.map &:to_i
a=gets.split.map &:to_i
b=gets.split.map &:to_i
tat=1
res=-1e18
for i in 0..n-1
  for j in 0..m-1
    if a[i]*b[j]>res
      res=a[i]*b[j]
      tat=i
    end
  end
end
res=-1e18.to_i
a[tat]=a[n-1]
for i in 0..n-2
  for j in b
    res=[res,a[i]*j].max
  end
end
p res

n, m=gets.split.map &:to_i
a=gets.split.map &:to_i
b=gets.split.map &:to_i
p (0...n).map{|i|b.map{|x| (0...n).select{|j|i!=j}.map{|j|a[j]*x}.max}.max}.min

n, m=gets.split.map &:to_i
a=gets.split.map &:to_i
b=gets.split.map &:to_i
p (0...n).map{ |i|
b.map{|x|
(0...n).select{ |j| i!=j }.map{|j|a[j]*x}.max}.max}.min

n,m=gets.split.map &:to_i
a=gets.split.map &:to_i
b=gets.split.map &:to_i
if a[0]==-1000000000
  p b[0]
end
tat=1
res=-1e18
for i in 0..n-1
  for j in 0..m-1
    if a[i]*b[j]>res
      res=a[i]*b[j]
      tat=i
    end
  end
end
res=-1e18
a[tat]=0
for i in a
  for j in b
    res=[res,i*j].max
  end
end
p res

n,m=gets.split.map &:to_i
a=gets.split.map &:to_i
b=gets.split.map &:to_i
tat=1
res=-1e18
for i in 0..n-1
  for j in 0..m-1
    if a[i]*b[j]>res
      res=a[i]*b[j]
      tat=i
    end
  end
end
res=-1e18
a[tat]=0
for i in a
  for j in b
    res=[res,i*j].max
  end
end
p res

n,m=gets.split.map &:to_i
a=gets.split.map &:to_i
b=gets.split.map &:to_i
tat=1
res=-1e9
for i in 0..n-1
  for j in 0..m-1
    if a[i]*b[j]>res
      res=a[i]*b[j]
      tat=i
    end
  end
end
res=-1e9
a[tat]=0
for i in a
  for j in b
    res=[res,i*j].max
  end
end
p res

n,m=gets.split.map &:to_i
a=gets.split.map &:to_i
b=gets.split.map &:to_i
if a[0]==-1000000000
  p b[0]
end
tat=1
res=-1e18
for i in 0..n-1
  for j in 0..m-1
    if a[i]*b[j]>res
      res=a[i]*b[j]
      tat=i
    end
  end
end
res=-1e18
a[tat]=a[n-1]
for i in 0..n-2
  for j in b
    res=[res,a[i]*j].max
  end
end
p res

n,m=gets.split.map &:to_i
a=gets.split.map &:to_i
b=gets.split.map &:to_i
tat=1
res=-1e18
for i in 0..n-1
  for j in 0..m-1
    if a[i]*b[j]>res
      res=a[i]*b[j]
      tat=i
    end
  end
end
res=-1e18
a[tat]=a[n-1]
for i in 0..n-2
  for j in b
    res=[res,a[i]*j].max
  end
end
p res

n,m=gets.split.map &:to_i
a=gets.split.map &:to_i
b=gets.split.map &:to_i
tat=1
res=-1e18
for i in 0..n-1
  for j in 0..m-1
    if a[i]*b[j]>res
      res=a[i]*b[j]
      tat=i
    end
  end
end
res=-1e18
a[tat]=0
for i in a
  for j in b
    if i!=tat
    res=[res,i*j].max
    end
  end
end
p res

n,m=gets.split.map &:to_i
a=gets.split.map &:to_i
b=gets.split.map &:to_i
if a[0]==-1000000000
  p b[0]
end
tat=1
res=-1e18
for i in 0..n-1
  for j in 0..m-1
    if a[i]*b[j]>res
      res=a[i]*b[j]
      tat=i
    end
  end
end
res=-1e18.to_i
a[tat]=a[n-1]
for i in 0..n-2
  for j in b
    res=[res,a[i]*j].max
  end
end
p res

n, m=gets.split.map &:to_i
a=gets.split.map &:to_i
b=gets.split.map &:to_i
a.delete a.max
puts a.max * b.max

n, m=gets.split.map &:to_i
a=gets.split.map &:to_i
b=gets.split.map &:to_i
a.sort!
puts a[n-2] * b.max


In this task you need to process a set of stock exchange orders and use them to create order book.An order is an instruction of some participant to buy or sell stocks on stock exchange. The order number i has price pi, direction di — buy or sell, and integer qi. This means that the participant is ready to buy or sell qi stocks at price pi for one stock. A value qi is also known as a volume of an order.All orders with the same price p and direction d are merged into one aggregated order with price p and direction d. The volume of such order is a sum of volumes of the initial orders.An order book is a list of aggregated orders, the first part of which contains sell orders sorted by price in descending order, the second contains buy orders also sorted by price in descending order.An order book of depth s contains s best aggregated orders for each direction. A buy order is better if it has higher price and a sell order is better if it has lower price. If there are less than s aggregated orders for some direction then all of them will be in the final order book.You are given n stock exhange orders. Your task is to print order book of depth s for these orders.

The input starts with two positive integers n and s (1 ≤ n ≤ 1000, 1 ≤ s ≤ 50), the number of orders and the book depth. Next n lines contains a letter di (either 'B' or 'S'), an integer pi (0 ≤ pi ≤ 105) and an integer qi (1 ≤ qi ≤ 104) — direction, price and volume respectively. The letter 'B' means buy, 'S' means sell. The price of any sell order is higher than the price of any buy order.

Print no more than 2s lines with aggregated orders from order book of depth s. The output format for orders should be the same as in input.

NoteDenote (x, y) an order with price x and volume y. There are 3 aggregated buy orders (10, 3), (20, 4), (25, 10) and two sell orders (50, 8), (40, 1) in the sample.You need to print no more than two best orders for each direction, so you shouldn't print the order (10 3) having the worst price among buy orders.

n,s = gets.split(" ").map(&:to_i)
sell = Hash.new(0)
buy = Hash.new(0)
n.times{
    ccc,p,q = gets.split(" ")
    p = p.to_i
    q = q.to_i
    if ccc == 'B'
        buy[p]+=q
    else
        sell[p]+=q
    end
}
ans = sell.keys.sort.take(s).reverse.map{|x| "S #{x} #{sell[x]}"}
ans += buy.keys.sort.last(s).reverse.map{|x| "B #{x} #{buy[x]}"}
puts ans

n,s=gets.split.map &:to_i
B={}
S={}
$<.map{|l|
  d,p,q=l.split
  (d==?B ? B : S)[p.to_i] ||= 0
  (d==?B ? B : S)[p.to_i] += q.to_i
}
S.sort_by{|k,v|k}[0,s].reverse.each{|k,v|puts"S #{k} #{v}"}
B.sort_by{|k,v|k}.reverse[0,s].each{|k,v|puts"B #{k} #{v}"}

# http://codeforces.com/contest/572/problem/B
n, m = gets.chomp.split.map(&:to_i)
b = Hash.new { 0 }
s = Hash.new { 0 }

n.times do
  d, p, q = gets.chomp.split
  p = p.to_i
  q = q.to_i
  b[p] += q if d == 'B'
  s[p] += q if d == 'S'
end

s.keys.sort.first(m).reverse.each do |key|
  puts ['S', key, s[key]].join(' ')
end

b.keys.sort.last(m).reverse.each do |key|
  puts ['B', key, b[key]].join(' ')
end

n, k = gets.split.map(&:to_i)
s = Hash.new(0)
b = Hash.new(0)
n.times do
    d, p, q = gets.split(' ')
    p = p.to_i
    q = q.to_i
    s[p] += q if (d=="S")
    b[p] += q if (d=="B")
end
s.sort.first(k).reverse_each{|x|
	puts "S #{x.first} #{x.last}"
}
b.sort.last(k).reverse_each{|x|
    puts "B #{x.first} #{x.last}"
}

n, k = gets.split.map(&:to_i)
s = Hash.new(0)
b = Hash.new(0)
n.times do
    d, p, q = gets.split(" ")
    p = p.to_i
    q = q.to_i
    s[p] += q if (d=="S")
    b[p] += q if (d=="B")
end
s.sort.first(k).reverse.each{|x|
	puts "S #{x.first} #{x.last}"
}
b.sort.last(k).reverse.each{|x|
    puts "B #{x.first} #{x.last}"
}

n, k = gets.split.map(&:to_i)
s = Hash.new(0)

b = Hash.new(0)
n.times do
    d, p, q = gets.split(" ")
    p = p.to_i
    q = q.to_i
    s[p] += q if (d=="S")
    b[p] += q if (d=="B")
end
s.sort.first(k).reverse_each{|x|
	puts "S #{x.first} #{x.last}"
}
b.sort.last(k).reverse_each{|x|
    puts "B #{x.first} #{x.last}"
}

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

s = Hash.new(0)
b = Hash.new(0)

n.times do
  d, p, q = gets.split
  p = p.to_i
  q = q.to_i
  s[p] += q if d == 'S'
  b[p] += q if d == 'B'
end
s.keys.sort.first(k).reverse_each { |e| puts "S #{e} #{s[e]}" }
b.keys.sort.last(k).reverse_each { |e| puts "B #{e} #{b[e]}" }

total_num, depth = *gets.chomp.split(" ").map(&:to_i)

aggregated = {
  'B' => {},
  'S' => {}
}

total_num.times do |index|
  input = gets.chomp.split(" ")
  direction, price, amount = input[0], input[1].to_i, input[2].to_i
  aggregated[direction][price] = aggregated[direction][price] ? aggregated[direction][price] + amount : amount
end

%w(S B).each do |direction|
  prices = aggregated[direction].keys.sort
  prices = direction == 'B' ? prices.reverse.first(depth) : prices.reverse.last(depth)
  prices.each { |price| puts "#{direction} #{price} #{aggregated[direction][price]}" }
end

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

ag_buy = {}
ag_sell = {}

n.times {
  dir, price, vol = gets.split(' ')
  price = price.to_i
  vol = vol.to_i
  ag = dir == "S" ? ag_sell : ag_buy
  ag[price] ||= 0
  ag[price] += vol
}

ar = ag_sell.keys.sort.take(s).reverse.map { |p| "S #{p} #{ag_sell[p]}" }
ar += ag_buy.keys.sort.last(s).reverse.map { |p| "B #{p} #{ag_buy[p]}" }

puts ar

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

s = Hash.new(0)
b = Hash.new(0)

n.times do
  d, p, q = gets.split.map{|e| e}
  p = p.to_i
  q = q.to_i

  s[p] += q if d == 'S'
  b[p] += q if d == 'B'
end

s.keys.sort.first(k).reverse_each{ |e| puts "S #{e} #{s[e]}" }
b.keys.sort.last(k).reverse_each{ |e| puts "B #{e} #{b[e]}" }

n, k = gets.split.map(&:to_i)
d, p, q = 0, 0, 0

s = Hash.new
b = Hash.new
s.default, b.default = 0, 0

for i in 1..n
  d, p, q = gets.split.map{|e| e}
  p = p.to_i
  q = q.to_i

  s[p] += q if d == 'S'
  b[p] += q if d == 'B'
end

out = ''

for i in 1..[k, s.size].min
  min = s.keys.min
  out = "S #{min} #{s[min]}\n" + out
  s.delete(min)
end

print out

for i in 1..[k, b.size].min
  max = b.keys.max
  puts "B #{max} #{b[max]}"
  b.delete(max)
end

n, k = gets.split.map(&:to_i)
d, p, q = 0, 0, 0

s = Hash.new
b = Hash.new

for i in 1..n
  d, p, q = gets.split.map{|e| e}
  p = p.to_i
  q = q.to_i

  if d == 'S'
    if s.has_key?(p)
      s[p] += q
    else
      s[p] = q
    end
  end

  if d == 'B'
    if b.has_key?(p)
      b[p] += q
    else
      b[p] = q
    end
  end
end

out = ''

for i in 1..[k, s.size].min
  min = s.keys.min
  out = "S #{min} #{s[min]}\n" + out
  s.delete(min)
end

print out

for i in 1..[k, b.size].min
  max = b.keys.max
  puts "B #{max} #{b[max]}"
  b.delete(max)
end

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

s,b = Hash.new(0),Hash.new(0)

n.times do
  d,p,q = gets.split(' ').map{|e| e}
  p,q = p.to_i,q.to_i

  s[p] += q if d == 'S'
  b[p] += q if d == 'B'
end

s.keys.sort.first(k).reverse_each{|e| puts "S #{e} #{s[e]}"}
b.keys.sort.last(k).reverse_each{ |e| puts "B #{e} #{b[e]}"}

n, s = gets.chomp.split(' ').map(&:to_i)
ds = []
ps = []
qs = []
n.times do
  d, p, q = gets.chomp.split(' ')
  ds << d
  ps << p.to_i
  qs << q.to_i
end

buy = Hash.new(0)
bp = []
sell = Hash.new(0)
sp = []
for i in 0..n-1
  if ds[i] == 'B'
    buy[ps[i]] += qs[i]
    bp << ps[i]
  else
    sell[ps[i]] += qs[i]
    sp << ps[i]
  end
end

bp.sort!.uniq!
sp.sort!.uniq!

ns = ([] << s << sp.size).min
for i in 0..ns - 1
  puts "S #{sp[ns - i - 1]} #{sell[sp[ns - i - 1]]}"
end

nb = ([] << s << bp.size).min
for i in 0..nb - 1
  puts "B #{bp[bp.size - i - 1]} #{buy[bp[bp.size - i - 1]]}"
end

n, s = gets.split.map(&:to_i)
a = n.times.map{gets.split.tap{|x| x[1], x[2] = x[1].to_i, x[2].to_i}}.sort_by{|x| x[1]}
buy, sell = a.partition{|x| x[0] == 'B'}
def f(a)
  a.group_by{|x| x[1]}
    .map{|_, x| [x[0][0], x[0][1], x.map(&:last).inject(:+)]}
end
buy = f(buy).reverse.take(s)
sell = f(sell).take(s).reverse

puts (sell + buy).map{|x| x.join(' ')}

n, s = gets.split.map(&:to_i)
a = n.times.map{gets.split}.sort_by{|x| x[1].to_i}
a.each{|x| x[1], x[2] = x[1].to_i, x[2].to_i}
buy, sell = a.partition{|x| x[0] == 'B'}
def f(a)
  b = a.group_by{|x| x[1]}
  b.map{|x| [x[1][0][0], x[1][0][1], x[1].reduce(0){|sum, y| sum + y[2]}]}
end
buy = f(buy).reverse[0...[s, buy.size].min]
sell = f(sell)[0...[s, sell.size].min].reverse

puts (sell + buy).map{|x| x.join(' ')}

#!/usr/bin/ruby

B = {}
S = {}

def algo
  n, s = gets.split(" ").map { |e| e.to_i }
  n.times.each do
    d, p, v = gets.split(" ")
    p = p.to_i
    v = v.to_i
    eval(d)[p] ||= 0
    eval(d)[p] += v
  end
  ks = S.keys.sort.take(s).reverse
  kb = B.keys.sort.reverse.take(s)
  ks.each { |e| puts "S #{e} #{S[e]}" }
  kb.each { |e| puts "B #{e} #{B[e]}" }
end

algo

n,s = gets.split(" ").map(&:to_i)
sell = Hash.new(0)
buy = Hash.new(0)
n.times{
    ccc,p,q = gets.split(" ")
    p = p.to_i
    q = q.to_i
    if ccc == 'B'
        buy[p]+=q
    else
        sell[p]+=q
    end
}
ans = sell.values.sort.last(s).reverse.map{|x| "S #{sell.index(x)} #{x}"}
ans += buy.values.sort.last(s).reverse.map{|x| "B #{buy.index(x)} #{x}"}
puts ans

n,s = gets.split(" ").map(&:to_i)
buy = Hash.new(0)
sell = Hash.new(0)
for i in 1..n
   ccc,p,q = gets.split(" ")
   p = p.to_i
   q = q.to_i
   if ccc=='B'
       buy[p]+=q
   else
       sell[p]+=q
   end
end
buy = buy.sort_by { |x, y| [ -Integer(y), x ] }
sell = sell.sort_by { |x, y| [ -Integer(y), x ] }
i=0
sell.each do |key,value|
    puts "S #{key} #{value}"
    i+=1
    if i==s || i==sell.size
        break
    end
end
i=0
buy.each do |key,value|
    puts "B #{key} #{value}"
    i+=1
    if i==s || i==buy.size
        break
    end
end

# http://codeforces.com/contest/572/problem/B
n, m = gets.chomp.split.map(&:to_i)
b = Hash.new { 0 }
s = Hash.new { 0 }

n.times do
  d, p, q = gets.chomp.split
  p = p.to_i
  q = q.to_i

  if d == 'B'
    b[p] += q
  else
    s[p] += q
  end
end

b = b.to_a.sort_by { |x, y| -(x * y) }
s = s.to_a.sort_by { |x, y| x * y }

(0...m).each do |idx|
  puts (['S'] + s[idx]).join(' ')
end

(0...m).each do |idx|
  puts (['B'] + b[idx]).join(' ')
end

n, k = gets.split.map(&:to_i)
s = Hash.new(0)
b = Hash.new(0)
n.times do
    d, p, q = gets.split(" ")
    p = p.to_i
    q = q.to_i
    s[p] += q if (d=="S")
    b[p] += q if (d=="B")
end
s.sort.first(k).each{|x|
    print "S "
    puts "#{x.first} #{x.last}"
}
b.sort.last(k).each{|x|
    print "B "
    puts "#{x.first} #{x.last}"
}

total_num, depth = *gets.chomp.split(" ").map(&:to_i)

aggregated = {
  'B' => {},
  'S' => {}
}

total_num.times do |index|
  input = gets.chomp.split(" ")
  direction, price, amount = input[0], input[1].to_i, input[2].to_i
  aggregated[direction][price] = aggregated[direction][price] ? aggregated[direction][price] + amount : amount
end

%w(S B).each do |direction|
  prices = aggregated[direction].keys.sort
  prices = prices.reverse if direction == 'B'
  prices.first(depth).each do |price|
    puts "#{direction} #{price} #{aggregated[direction][price]}"
  end
end

total_num, depth = *gets.chomp.split(" ").map(&:to_i)

aggregated = {
  'B' => {},
  'S' => {}
}

total_num.times do |index|
  input = gets.chomp.split(" ")
  direction, price, amount = input[0], input[1].to_i, input[2].to_i
  aggregated[direction][price] = aggregated[direction][price] ? aggregated[direction][price] + amount : amount
end

%w(S B).each do |direction|
  aggregated[direction].keys.sort.reverse.first(depth).each do |price|
  	puts "#{direction} #{price} #{aggregated[direction][price]}"
  end
end

n, k = gets.split.map(&:to_i)
d, p, q = 0, 0, 0

s = Hash.new
b = Hash.new

for i in 1..n
  d, p, q = gets.split.map{|e| e}
  q = q.to_i

  if d == 'S'
    if s.has_key?(p)
      s[p] += q
    else
      s[p] = q
    end
  end

  if d == 'B'
    if b.has_key?(p)
      b[p] += q
    else
      b[p] = q
    end
  end
end

out = ''

for i in 1..[k, s.size].min
  min = s.keys.min
  out = "S #{min} #{s[min]}\n" + out
  s.delete(min)
end

print out

for i in 1..[k, b.size].min
  max = b.keys.max
  puts "B #{max} #{b[max]}"
  b.delete(max)
end

n, k = gets.split.map(&:to_i)
d, p, q = 0, 0, 0

s = Hash.new
b = Hash.new

for i in 1..n
  d, p, q = gets.split.map{|e| e}
  q = q.to_i

  if d == 'S'
    if s.has_key?(p)
      s[p] += q
    else
      s[p] = q
    end
  end

  if d == 'B'
    if b.has_key?(p)
      b[p] += q
    else
      b[p] = q
    end
  end
end

out = ''

for i in 1..[k, s.size].min
  min = s.keys.min
  out = "S #{min} #{s[min]}\n" + out
  s.delete(min)
end

puts out

for i in 1..[k, b.size].min
  max = b.keys.max
  puts "B #{max} #{b[max]}"
  b.delete(max)
end

n, s = gets.chomp.split(' ').map(&:to_i)
ds = []
ps = []
qs = []
n.times do
  d, p, q = gets.chomp.split(' ')
  ds << d
  ps << p.to_i
  qs << q.to_i
end

buy = Hash.new(0)
bp = []
sell = Hash.new(0)
sp = []
for i in 0..n-1
  if ds[i] == 'B'
    buy[ps[i]] += qs[i]
    bp << ps[i]
  else
    sell[ps[i]] += qs[i]
    sp << ps[i]
  end
end

bp.sort!.uniq!
sp.sort!.uniq!

for i in 0..([] << s << sp.size).min - 1
  puts "S #{sp[sp.size-i-1]} #{sell[sp[s-i-1]]}"
end

for i in 0..([] << s << bp.size).min - 1
  puts "B #{bp[bp.size-i-1]} #{buy[bp[bp.size-i-1]]}"
end

n, s = gets.chomp.split(' ').map(&:to_i)
ds = []
ps = []
qs = []
n.times do
  d, p, q = gets.chomp.split(' ')
  ds << d
  ps << p.to_i
  qs << q.to_i
end

buy = Hash.new(0)
bp = []
sell = Hash.new(0)
sp = []
for i in 0..n-1
  if ds[i] == 'B'
    buy[ps[i]] += qs[i]
    bp << ps[i]
  else
    sell[ps[i]] += qs[i]
    sp << ps[i]
  end
end

bp.sort!.uniq!
sp.sort!.uniq!

for i in 0..([] << s << sp.size).min - 1
  puts "S #{sp[s-i-1]} #{sell[sp[s-i-1]]}"
end

for i in 0..([] << s << bp.size).min - 1
  puts "B #{bp[bp.size-i-1]} #{buy[bp[bp.size-i-1]]}"
end

n, s = gets.chomp.split(' ').map(&:to_i)
ds = []
ps = []
qs = []
n.times do
  d, p, q = gets.chomp.split(' ')
  ds << d
  ps << p.to_i
  qs << q.to_i
end

buy = Hash.new(0)
bp = []
sell = Hash.new(0)
sp = []
for i in 0..n-1
  if ds[i] == 'B'
    buy[ps[i]] += qs[i]
    bp << ps[i]
  else
    sell[ps[i]] += qs[i]
    sp << ps[i]
  end
end

bp.sort!.uniq!
sp.sort!.uniq!

for i in 0..([] << s << sp.size).min - 1
  puts "S #{sp[sp.size-i-1]} #{sell[sp[sp.size-i-1]]}"
end

for i in 0..([] << s << bp.size).min - 1
  puts "B #{bp[bp.size-i-1]} #{buy[bp[bp.size-i-1]]}"
end

n,s=gets.split.map &:to_i
B={}
S={}
$<.map{|l|
  d,p,q=l.split
  (d==?B ? B : S)[p.to_i] ||= 0
  (d==?B ? B : S)[p.to_i] += q.to_i
}
S.sort_by{|k,v|k}.reverse[0,s].each{|k,v|puts"S #{k} #{v}"}
B.sort_by{|k,v|k}.reverse[0,s].each{|k,v|puts"B #{k} #{v}"}

n,s=gets.split.map &:to_i
B={}
S={}
$<.map{|l|
  d,p,q=l.split
  (d==?B ? B : S)[p.to_i] ||= 0
  (d==?B ? B : S)[p.to_i] += q.to_i
}
S.sort_by{|k,v|v}.reverse[0,s].each{|k,v|puts"S #{k} #{v}"}
B.sort_by{|k,v|v}.reverse[0,s].each{|k,v|puts"B #{k} #{v}"}

#!/usr/bin/ruby

B = {}
S = {}

def algo
  n, s = gets.split(" ").map { |e| e.to_i }
  n.times.each do
    d, p, v = gets.split(" ")
    p = p.to_i
    v = v.to_i
    eval(d)[p] ||= 0
    eval(d)[p] += v
  end
  ks = S.keys.sort.reverse.take(s)
  kb = B.keys.sort.reverse.take(s)
  ks.each { |e| puts "S #{e} #{S[e]}" }
  kb.each { |e| puts "B #{e} #{B[e]}" }
end

algo

#!/usr/bin/ruby

B = {}
S = {}

def algo
  n, s = gets.split(" ").map { |e| e.to_i }
  n.times.each do
    d, p, v = gets.split(" ")
    p = p.to_i
    v = v.to_i
    eval(d)[p] ||= 0
    eval(d)[p] += v
  end
  ks = S.keys.sort.take(s)
  kb = B.keys.sort.reverse.take(s)
  ks.each { |e| puts "S #{e} #{S[e]}" }
  kb.each { |e| puts "B #{e} #{B[e]}" }
end

algo


As we all know, Winnie-the-Pooh just adores honey. Ones he and the Piglet found out that the Rabbit has recently gotten hold of an impressive amount of this sweet and healthy snack. As you may guess, Winnie and the Piglet asked to come at the Rabbit's place. Thus, there are n jars of honey lined up in front of Winnie-the-Pooh, jar number i contains ai kilos of honey. Winnie-the-Pooh eats the honey like that: each time he chooses a jar containing most honey. If the jar has less that k kilos of honey or if Winnie-the-Pooh has already eaten from it three times, he gives the jar to Piglet. Otherwise he eats exactly k kilos of honey from the jar and puts it back. Winnie does so until he gives all jars to the Piglet. Count how much honey Piglet will overall get after Winnie satisfies his hunger.

The first line contains two integers n and k (1 ≤ n ≤ 100, 1 ≤ k ≤ 100). The second line contains n integers a1, a2, ..., an, separated by spaces (1 ≤ ai ≤ 100).

Print a single number — how many kilos of honey gets Piglet.

f = File.open('input.txt', 'r') or die "Unable to open file..."
input = []  # start with an empty array
  f.each_line {|line|
    input.push line
  }

k = input[0].scan(/\w+/)[1].to_i
jars = input[1].scan(/\w+/).map!(&:to_i)
total = jars.inject(0) do |give, jar|
 nom = 0
 until jar < k or nom == 3 do
 jar = jar - k
 nom += 1
 end

 if jar < k or nom == 3
 give += jar
 end

end

 File.open('output.txt', 'w') { |o| o.puts total}

STDIN.reopen 'input.txt'
STDOUT.reopen 'output.txt'
N, K = gets.split.map &:to_i
A = gets.split.map &:to_i
p A.map { |v| v - [v / K, 3].min * K }.reduce :+

if File.exist?('input.txt')
  input = IO.readlines("input.txt")
  input.each do |word|
    word.delete!("\n")
  end
end
input1 = input[0]
input2 = input[1]

# a = []

k = input1.split(" ")[1].to_i

piglet_honey = 0

input2.split(" ").each do |e|

  if e.to_i > 3*k
    piglet_honey += e.to_i - 3*k
  else
    piglet_honey += e.to_i%k
  end
end

output = File.open( "output.txt","w" )
output << piglet_honey
output.close

$stdin.reopen 'input.txt'
$stdout.reopen 'output.txt'
N, K = gets.split.map &:to_i
A = gets.split.map &:to_i
p A.map { |v| v - [v / K, 3].min * K }.reduce :+

$stdin.reopen('input.txt')
$stdout.reopen('output.txt')
N, K = gets.split.map &:to_i
A = gets.split.map &:to_i
p A.map { |v| v - [v / K, 3].min * K }.reduce :+

n, k, a = nil
File.open("input.txt") do |f|
  n, k = f.gets.split.map(&:to_i)
  a = f.gets.split.map(&:to_i)
end

s = a.inject(0){|r, x| r+(x>=3*k ? x-3*k : x%k)}

File.open("output.txt", "w") do |f|
  f.puts s
end

require 'scanf'

input = open("input.txt")

line = input.gets
l1 = line.scanf("%d %d")
n = l1[0]
k = l1[1]

line = input.gets
a = line.scan(/[\d]+/)

ret = 0

a.each do |i|
  ret += [i.to_i % k, i.to_i - 3 * k].max
end

output = open("output.txt", "w")
output.printf "%d\n" % [ret]


An undirected graph is called k-regular, if the degrees of all its vertices are equal k. An edge of a connected graph is called a bridge, if after removing it the graph is being split into two connected components.Build a connected undirected k-regular graph containing at least one bridge, or else state that such graph doesn't exist.

The single line of the input contains integer k (1 ≤ k ≤ 100) — the required degree of the vertices of the regular graph.

Print "NO" (without quotes), if such graph doesn't exist.  Otherwise, print "YES" in the first line and the description of any suitable graph in the next lines. The description of the made graph must start with numbers n and m — the number of vertices and edges respectively.  Each of the next m lines must contain two integers, a and b (1 ≤ a, b ≤ n, a ≠ b), that mean that there is an edge connecting the vertices a and b. A graph shouldn't contain multiple edges and edges that lead from a vertex to itself. A graph must be connected, the degrees of all vertices of the graph must be equal k. At least one edge of the graph must be a bridge. You can print the edges of the graph in any order. You can print the ends of each edge in any order. The constructed graph must contain at most 106 vertices and 106 edges (it is guaranteed that if at least one graph that meets the requirements exists, then there also exists the graph with at most 106 vertices and at most 106 edges).

NoteIn the sample from the statement there is a suitable graph consisting of two vertices, connected by a single edge.

#!/usr/bin/ruby

def read_vector
    gets.split(/\s+/)
end

def read_vector_int
    read_vector.map(&:to_i)
end

n = gets.to_i
if n % 2 == 0 then
    puts "NO"
    exit
end

puts "YES"
if n == 1 then
    puts <<EOF
2 1
2 1
EOF
    exit
end

$g = []
$res = []
$maxv = 0
def add_edge(u, v)
    $res.push([u, v])
    $g[u] = $g[u].to_a + [v]
    $g[v] = $g[v].to_a + [u]
    $maxv = [$maxv, u, v].max
end

add_edge(0, 1)
add_edge(0, 2)
add_edge(3, 4)
add_edge(1, 3)
add_edge(1, 4)
add_edge(2, 3)
add_edge(2, 4)
(5..n).step(2).each do |i|
    a, b = i, i + 1
    i.times{ |j| add_edge(a, j); add_edge(b, j) }
end

mid = $maxv + 1
mid.times{ |v| $g[v].select{ |u| u > v }.each{ |u| add_edge(v + mid, u + mid) } }
add_edge(0, mid)

puts "#{$maxv + 1} #{$res.size}"
puts $res.map{ |a| "#{a[0] + 1} #{a[1] + 1}" }.join("\n")

#!/usr/bin/ruby

def read_vector
    gets.split(/\s+/)
end

def read_vector_int
    read_vector.map(&:to_i)
end

n = gets.to_i
if n % 2 == 0 then
    puts "NO"
    exit
end

puts "YES"
if n == 1 then
    puts <<EOF
2 1
2 1
EOF
    exit
end

$g = []
$res = []
$maxv = 0
def add_edge(u, v)
    $res.push([u, v])
    $g[u] = $g[u].to_a + [v]
    $g[v] = $g[v].to_a + [u]
    $maxv = [$maxv, u, v].max
end

add_edge(0, 1)
add_edge(0, 2)
add_edge(3, 4)
add_edge(1, 3)
add_edge(1, 4)
add_edge(2, 3)
add_edge(2, 4)
(5..n).step(2).each do |i|
    a, b = i, i + 1
    i.times{ |j| add_edge(a, j); add_edge(b, j) }
end

mid = $maxv
mid.times{ |v| $g[v].select{ |u| u > v }.each{ |u| add_edge(v + mid, u + mid) } }
add_edge(0, mid)

puts "#{$maxv + 1} #{$res.size}"
puts $res.map{ |a| "#{a[0] + 1} #{a[1] + 1}" }.join("\n")


You have got a shelf and want to put some books on it.You are given $$$q$$$ queries of three types:  L $$$id$$$ — put a book having index $$$id$$$ on the shelf to the left from the leftmost existing book;  R $$$id$$$ — put a book having index $$$id$$$ on the shelf to the right from the rightmost existing book;  ? $$$id$$$ — calculate the minimum number of books you need to pop from the left or from the right in such a way that the book with index $$$id$$$ will be leftmost or rightmost. You can assume that the first book you will put can have any position (it does not matter) and queries of type $$$3$$$ are always valid (it is guaranteed that the book in each such query is already placed). You can also assume that you don't put the same book on the shelf twice, so $$$id$$$s don't repeat in queries of first two types.Your problem is to answer all the queries of type $$$3$$$ in order they appear in the input.Note that after answering the query of type $$$3$$$ all the books remain on the shelf and the relative order of books does not change.If you are Python programmer, consider using PyPy instead of Python when you submit your code.

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 2 \cdot 10^5$$$) — the number of queries. Then $$$q$$$ lines follow. The $$$i$$$-th line contains the $$$i$$$-th query in format as in the problem statement. It is guaranteed that queries are always valid (for query type $$$3$$$, it is guaranteed that the book in each such query is already placed, and for other types, it is guaranteed that the book was not placed before). It is guaranteed that there is at least one query of type $$$3$$$ in the input. In each query the constraint $$$1 \le id \le 2 \cdot 10^5$$$ is met.

Print answers to queries of the type $$$3$$$ in order they appear in the input.

NoteLet's take a look at the first example and let's consider queries:   The shelf will look like $$$[1]$$$;  The shelf will look like $$$[1, 2]$$$;  The shelf will look like $$$[1, 2, 3]$$$;  The shelf looks like $$$[1, \textbf{2}, 3]$$$ so the answer is $$$1$$$;  The shelf will look like $$$[4, 1, 2, 3]$$$;  The shelf looks like $$$[4, \textbf{1}, 2, 3]$$$ so the answer is $$$1$$$;  The shelf will look like $$$[5, 4, 1, 2, 3]$$$;  The shelf looks like $$$[5, 4, \textbf{1}, 2, 3]$$$ so the answer is $$$2$$$. Let's take a look at the second example and let's consider queries:   The shelf will look like $$$[100]$$$;  The shelf will look like $$$[100, 100000]$$$;  The shelf will look like $$$[100, 100000, 123]$$$;  The shelf will look like $$$[101, 100, 100000, 123]$$$;  The shelf looks like $$$[101, 100, 100000, \textbf{123}]$$$ so the answer is $$$0$$$;  The shelf will look like $$$[10, 101, 100, 100000, 123]$$$;  The shelf will look like $$$[10, 101, 100, 100000, 123, 115]$$$;  The shelf looks like $$$[10, 101, \textbf{100}, 100000, 123, 115]$$$ so the answer is $$$2$$$;  The shelf will look like $$$[10, 101, 100, 100000, 123, 115, 110]$$$;  The shelf looks like $$$[10, 101, 100, 100000, 123, \textbf{115}, 110]$$$ so the answer is $$$1$$$.

def solution
  n = read_int

  left = 500_000
  right = left + 1
  shelf = {}

  n.times do
    command, id = read_string.split
    case command
    when ?L
      shelf[id] = left
      left -= 1
    when ?R
      shelf[id] = right
      right += 1
    when ??
      pos = shelf[id]
      puts [pos - left - 1, right - pos - 1].min
    end

  end

end

def read_int
  gets.to_i
end

def read_ints
  gets.split.map(&:to_i)
end

def read_string
  gets.chomp
end

solution unless ENV['TEST__MODE']

$h = Hash.new(0)
$l = 0
$r = 0

def solve
  type, id = gets.strip.split(' ')
  id = id.to_i
  if type == "L"
    $l += 1
    $h[[id, 0]] = $l
  elsif type == "R"
    $r += 1
    $h[[id, 1]] = $r
  else
    flg_left = false; flg_right = false
    if $h[[id, 0]].zero? && !$h[[id, 1]].zero?
      ok = $h[[id, 1]]
      flg_right = true
    elsif !$h[[id, 0]].zero? && $h[[id, 1]].zero?
      flg_left = true
      ok = $h[[id, 0]]
    end
    if flg_left == true
      s = [$l - ok, ok - 1 + $r].min
      puts s
    elsif flg_right == true
      s = [$r - ok, ok - 1 + $l].min
      puts s
    end
  end
end

gets.strip.to_i.times { solve }

$h = Hash.new(0)
$l = 0
$r = 0

def solve
  type, id = gets.strip.split(' ')
  id = id.to_i
  if type == "L"
    $l += 1
    $h[[id, 0]] = $l
  elsif type == "R"
    $r += 1
    $h[[id, 1]] = $r
  else
    ok = -1
    flg_left = false; flg_right = false
    if $h[[id, 0]].zero? && !$h[[id, 1]].zero?
      ok = $h[[id, 1]]
      flg_right = true
    elsif !$h[[id, 0]].zero? && $h[[id, 1]].zero?
      flg_left = true
      ok = $h[[id, 0]]
    end
    if flg_left == true
      s = [$l - ok, $l - ok + $r].min
      puts s
    elsif flg_right == true
      s = [$r - ok, $r - ok + $l].min
      puts s
    end
  end
end

gets.strip.to_i.times { solve }


You are given a permutation $$$p_1, p_2, \ldots, p_n$$$ of length $$$n$$$. You have to choose two integers $$$l,r$$$ ($$$1 \le l \le r \le n$$$) and reverse the subsegment $$$[l,r]$$$ of the permutation. The permutation will become $$$p_1,p_2, \dots, p_{l-1},p_r,p_{r-1}, \dots, p_l,p_{r+1},p_{r+2}, \dots ,p_n$$$.Find the lexicographically smallest permutation that can be obtained by performing exactly one reverse operation on the initial permutation.Note that for two distinct permutations of equal length $$$a$$$ and $$$b$$$, $$$a$$$ is lexicographically smaller than $$$b$$$ if at the first position they differ, $$$a$$$ has the smaller element.A permutation is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2,3,1,5,4]$$$ is a permutation, but $$$[1,2,2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1,3,4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array).

Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. Description of the test cases follows. The first line of each test case contains a single integer $$$n$$$ ($$$1 \le n \le 500$$$) — the length of the permutation. The second line of each test case contains $$$n$$$ integers $$$p_1, p_2, \dots, p_n$$$ ($$$1 \le p_i \le n$$$) — the elements of the permutation.

For each test case print the lexicographically smallest permutation you can obtain.

NoteIn the first test case, the permutation has length $$$1$$$, so the only possible segment is $$$[1,1]$$$. The resulting permutation is $$$[1]$$$.In the second test case, we can obtain the identity permutation by reversing the segment $$$[1,2]$$$. The resulting permutation is $$$[1,2,3]$$$.In the third test case, the best possible segment is $$$[2,3]$$$. The resulting permutation is $$$[1,2,4,3]$$$.In the fourth test case, there is no lexicographically smaller permutation, so we can leave it unchanged by choosing the segment $$$[1,1]$$$. The resulting permutation is $$$[1,2,3,4,5]$$$.

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

inputs.each_slice(2) do |inp|
  nums = inp[1].split(' ').map(&:to_i)
  if nums.size < 2
    puts nums.join(' ')
    next
  end

  sorted = nums.sort.join(' ')
  if nums.join(' ') == sorted
    puts sorted
    next
  end

  vals = []
  nums.each_with_index do |v, i|
    following = nums[i+1..]
    min = following.min
    if v < min
      vals << v
      next
    end

    index_min = nums.index(min)
    flip = nums[i..index_min].reverse
    vals += flip
    vals += nums[index_min+1..]

    break
  end

  puts vals.join(' ')
end

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

inputs.each_slice(2) do |inp|
  nums = inp[1].split(' ').map(&:to_i)
  if nums.size < 2
    puts nums.join(' ')
    next
  end

  nums.each_with_index do |v, i|
    break if nums.length == i + 1
    next if nums[i] < nums[i + 1]

    nums[i], nums[i + 1] = nums[i + 1], nums[i]

    break
  end

  puts nums.join(' ')
end


A sequence of brackets is called balanced if one can turn it into a valid math expression by adding characters '+' and '1'. For example, sequences '(())()', '()', and '(()(()))' are balanced, while ')(', '(()', and '(()))(' are not.You are given a binary string $$$s$$$ of length $$$n$$$. Construct two balanced bracket sequences $$$a$$$ and $$$b$$$ of length $$$n$$$ such that for all $$$1\le i\le n$$$:   if $$$s_i=1$$$, then $$$a_i=b_i$$$  if $$$s_i=0$$$, then $$$a_i\ne b_i$$$ If it is impossible, you should report about it.

The first line contains a single integer $$$t$$$ ($$$1\le t\le 10^4$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$2\le n\le 2\cdot 10^5$$$, $$$n$$$ is even). The next line contains a string $$$s$$$ of length $$$n$$$, consisting of characters 0 and 1. The sum of $$$n$$$ across all test cases does not exceed $$$2\cdot 10^5$$$.

If such two balanced bracked sequences exist, output "YES" on the first line, otherwise output "NO". You can print each letter in any case (upper or lower). If the answer is "YES", output the balanced bracket sequences $$$a$$$ and $$$b$$$ satisfying the conditions on the next two lines. If there are multiple solutions, you may print any.

NoteIn the first test case, $$$a=$$$"()()()" and $$$b=$$$"((()))". The characters are equal in positions $$$1$$$, $$$3$$$, $$$4$$$, and $$$6$$$, which are the exact same positions where $$$s_i=1$$$.In the second test case, $$$a=$$$"()()((()))" and $$$b=$$$"(())()()()". The characters are equal in positions $$$1$$$, $$$4$$$, $$$5$$$, $$$7$$$, $$$8$$$, $$$10$$$, which are the exact same positions where $$$s_i=1$$$.In the third test case, there is no solution.

gets.to_i.times do
  n=gets.to_i
  s=gets.chomp.chars
  if s[0]=="1"&&s[-1]=="1"&&s.count("1").even?
    puts "YES"
    ss=s.count("1")/2
    i=0
    a1l=""
    a2l=""
    aa=0
    c1=0
    while c1<ss
      if s[i]=="1"
        c1+=1
      end
      if s[i]=="1"
        a1l << "("
        a2l << "("
      else
        if aa==0
          a1l << "("
          a2l << ")"
          aa=1
        else
          a1l << ")"
          a2l << "("
          aa=0
        end
      end
      i+=1
    end
    j=n-1
    a1r=""
    a2r=""
    aa=0
    while i<=j
      if s[j]=="1"
        a1r << ")"
        a2r << ")"
      else
        if aa==0
          a1r << ")"
          a2r << "("
          aa=1
        else
          a1r << "("
          a2r << ")"
          aa=0
        end
      end
      j-=1
    end
    puts a1l+a1r.reverse
    puts a2l+a2r.reverse
  else
    puts "NO"
  end
end


One foggy Stockholm morning, Karlsson decided to snack on some jam in his friend Lillebror Svantenson's house. Fortunately for Karlsson, there wasn't anybody in his friend's house. Karlsson was not going to be hungry any longer, so he decided to get some food in the house.Karlsson's gaze immediately fell on n wooden cupboards, standing in the kitchen. He immediately realized that these cupboards have hidden jam stocks. Karlsson began to fly greedily around the kitchen, opening and closing the cupboards' doors, grab and empty all the jars of jam that he could find.And now all jars of jam are empty, Karlsson has had enough and does not want to leave traces of his stay, so as not to let down his friend. Each of the cupboards has two doors: the left one and the right one. Karlsson remembers that when he rushed to the kitchen, all the cupboards' left doors were in the same position (open or closed), similarly, all the cupboards' right doors were in the same position (open or closed). Karlsson wants the doors to meet this condition as well by the time the family returns. Karlsson does not remember the position of all the left doors, also, he cannot remember the position of all the right doors. Therefore, it does not matter to him in what position will be all left or right doors. It is important to leave all the left doors in the same position, and all the right doors in the same position. For example, all the left doors may be closed, and all the right ones may be open.Karlsson needs one second to open or close a door of a cupboard. He understands that he has very little time before the family returns, so he wants to know the minimum number of seconds t, in which he is able to bring all the cupboard doors in the required position.Your task is to write a program that will determine the required number of seconds t.

The first input line contains a single integer n — the number of cupboards in the kitchen (2 ≤ n ≤ 104). Then follow n lines, each containing two integers li and ri (0 ≤ li, ri ≤ 1). Number li equals one, if the left door of the i-th cupboard is opened, otherwise number li equals zero. Similarly, number ri equals one, if the right door of the i-th cupboard is opened, otherwise number ri equals zero. The numbers in the lines are separated by single spaces.

In the only output line print a single integer t — the minimum number of seconds Karlsson needs to change the doors of all cupboards to the position he needs.

def min(x, y)
    if x < y then
        return x
    else
        return y
    end
end

n = gets.to_i

left_open = 0
left_close = 0
right_open = 0
right_close = 0
n.times do |i|
    s = gets.split.collect{|j| j.to_i}
    if s[0] == 1 then
        left_open += 1
    else
        left_close += 1
    end
    if s[1] == 1 then
        right_open += 1
    else
        right_close += 1
    end
end
right = min(right_close, right_open)
left = min(left_close, left_open)
t = right + left
puts t

n=gets.to_i
a,b=0,0
n.times{
	c,d=gets.split.map(&:to_i)
	a += c
	b += d
}
puts [a,n-a].min + [b,n-b].min

n,a = gets.to_i ,Array.new{|el| el=Array.new(2)}
n.times{a<<gets.split.map(&:to_i)}
puts n-[a.find_all{|el| el[0]==0}.size,a.find_all{|el| el[0]==1}.size].max+(n-[a.find_all{|el| el[1]==0}.size,a.find_all{|el| el[1]==1}.size].max)

n = gets.chomp.to_i
right = 0
left = 0

n.times do
  l, r = gets.chomp.split(" ").map{|n| n.to_i}
  left += 1 if l == 0
  right += 1 if r == 0
end

puts [(n - left), left].min + [(n - right), right].min

n = gets.to_i
left = 0
right = 0
n.times do
  l, r = gets.split.map(&:to_i)
  left += l
  right += r
end
print [left, n-left].min + [right, n-right].min

def count(a,d)
  tot = 0
  if  a > d/2
    tot = d-a
  else
    # as the doors opened are fewer we need to count that amount of time to close them
    tot = a
  end
  tot
end

def calculate(n,l,r)
  # I choose to count 1s and then do the calculation for both sides
  lopens = l.count(1)
  ropens = r.count(1)
  tot_sec = 0

  tot_sec += count(lopens,n)
  tot_sec += count(ropens,n)

  tot_sec
end

n = gets.to_i
r = []
l = []
(1..n).each do
  a,b = gets.split(/\s/).map(&:to_i)
  l << a
  r << b
end

puts calculate(n,l,r)

n=gets.chomp.to_i
l1=0
l2=0
r1=0
r2=0
n.times do
	l,r=gets.chomp.split.map(&:to_i)
	if l!=0
		l1+=1
	else
		l2+=1
	end
	if r!=0
		r1+=1
	else
		r2+=1
	end
end
puts [l1,l2].min+[r1,r2].min

n = gets.to_i
a = readlines.map(&:chomp).map(&:split).each {|x| x.map!(&:to_i)}.transpose
puts [a[0].find_all {|x| x==0}.size, a[0].find_all {|x| x==1}.size].min +
    [a[1].find_all {|x| x==0}.size, a[1].find_all {|x| x==1}.size].min

n = gets.to_i
ret = 0
left =  [0,0]
right = [0,0]
for i in 0 .. n - 1
  line = gets
  if line.split(" ")[0].to_i == 0
    left[0] += 1
  else
    left[1] += 1
  end
  if line.split(" ")[1].to_i == 0
    right[0] += 1
  else
    right[1] += 1
  end
end

if left[0] < left[1]
  ret += left[0]
else
  ret += left[1]
end
if right[0] < right[1]
  ret += right[0]
else
  ret += right[1]
end

puts ret

n = gets.strip.to_i
left_open = left_close = right_open = right_close = 0
n.times do
    l, r = gets.strip.split.map(&:to_i)
    left_close += 1 if l == 0
    left_open += 1 if l == 1
    right_close += 1 if r == 0
    right_open += 1 if r == 1
end
ans = [left_open, left_close].min + [right_open, right_close].min
puts ans

a = gets.chomp.to_i
s = []
y = []; z=[]
rez=0
(0..a-1).each do |i|
  s = gets.chomp.split(' ')
  y[i]=s[0].to_i; z[i]=s[1].to_i
end

sum1 = y.inject(0){|sum, t| sum + t }
sum2 = z.inject(0){|sum, t| sum + t }

if a%2 != 0
  a1=a+1
else
  a1=a
end

if sum1>=a1/2
  rez+=a-sum1
else
  rez+=sum1
end

if sum2>=a1/2
  rez+=a-sum2
else
  rez+=sum2
end
puts rez

require 'set'
require 'rational'
require 'mathn'
include Math
$stdin = File.open("./input.txt", "r") if ENV["USER"] == "new"
# ====================================

n = gets.to_i
data = []

left_open = 0
right_open = 0
n.times{
  left, right = gets.split.map(&:to_i)

  left_open+=left
  right_open+=right
}

left_closed = n - left_open
right_closed = n - right_open

print [left_open, left_closed].min + [right_open, right_closed].min

require 'set'
require 'rational'
require 'mathn'
include Math
$stdin = File.open("./input.txt", "r") if ENV["USER"] == "new"
# ====================================

n = gets.to_i
data = []

n.times{
  data << gets.split.map(&:to_i)
}

left_open = 0
right_open = 0
data.each{|left, right|
  left_open+=left
  right_open+=right
}

left_closed = n - left_open
right_closed = n - right_open

print [left_open, left_closed].min + [right_open, right_closed].min

n=gets.to_i
a=b=0
n.times {
	l,r=gets.split.map(&:to_i)
	a+=1 if l==0
	b+=1 if r==0
}
puts ([a,n-a].min + [b,n-b].min)

n=gets.to_i
a,b=0,0
n.times{
	c,d=gets.split.map(&:to_i)
	a +=1 if c == 1
	b +=1 if d == 1
}
puts [a,n-a].min + [b,n-b].min

state_amount = 2
col_amount = 2
row_amount = gets.strip.to_i

state_count = Array.new(col_amount) { Array.new(state_amount, 0) }

1.upto(row_amount).each do |row|
  row_states = gets.strip.split(' ')
  row_states.each_with_index do |state, col|
    state_count[col][state.to_i] += 1
  end
end

movement_count = 0
1.upto(col_amount) do |col|
  movement_count += row_amount - state_count[col - 1].max
end

puts movement_count

n = Integer(gets)
a = Array.new
for i in 0...n
    a[i] = Array.new
    input = gets.chomp
    nums = input.split
    for j in 0...2
        a[i][j] = Integer(nums[j])
    end
end

amount_0 = 0
amount_1 = 0
for i in 0...n
    if a[i][0] == 0
        amount_0 += 1
    end
end
for i in 0...n
    if a[i][1] == 0
        amount_1 += 1
    end
end
ans1 = 0
if amount_0 <= n - amount_0
    ans1 = amount_0
else
    ans1 = n - amount_0
end
ans2 = 0
if amount_1 <= n - amount_1
    ans2 = amount_1
else
    ans2 = n - amount_1
end
puts ans1 + ans2

#file_contents = File.read('test.in')
n = gets.to_i

left_count = right_count = 0
n.times do
  l, r = gets.split.map(&:to_i)
  left_count += l
  right_count += r
end
puts [left_count, n - left_count].min + [right_count, n - right_count].min

zeros = [0, 0]
n = gets.chomp.to_i
for _ in 1..n
  gets.chomp.split.each_with_index { |x, i| zeros[i] += 1 if x == '0' }
end
puts zeros.map { |z| [z, n - z].min }.inject(:+)

n = gets.to_i

l = Array.new(n)
r = Array.new(n)

n.times do |i|
	t = gets.split.collect{|x| x.to_i}
	l[i] = t[0]
	r[i] = t[1]
end

lr = l.inject { |s,x| s+x }
rr = r.inject { |s,x| s+x}

puts [n - lr, lr].min + [n - rr, rr].min

n = gets.chomp.to_i
right = 0
left = 0

n.times do
  l, r = gets.chomp.split(" ").map{|n| n.to_i}
  left += 1 if l == 0
  right += 1 if r == 0
end

puts [left, right].max

n = gets.to_i
ret = 0
for i in 0 .. n - 1
  line = gets
  for j in 0 .. 1
    if line.split(" ")[j].to_i == 1
      ret += 0.5
    end
  end
end

puts ret.to_i

n = Integer(gets)
a = Array.new
for i in 0...n
    a[i] = Array.new
    input = gets.chomp
    nums = input.split
    for j in 0...2
        a[i][j] = Integer(nums[j])
    end
end

left1 = 0
left2 = 0
for i in 0...n
    if a[i][0] == 0
        left1 += 1
    end
end
for i in 0...n
    if a[i][1] == 1
        left2 += 1
    end
end
left = left1 + left2
if left >= 2*n - left
    puts 2*n - left
else
    puts left
end

n = Integer(gets)
a = Array.new
for i in 0...n
    a[i] = Array.new
    input = gets.chomp
    nums = input.split
    for j in 0...2
        a[i][j] = Integer(nums[j])
    end
end

left1 = 0
left2 = 0
for i in 0...n
    if a[i][0] == 0
        left1 += 1
    end
end
for i in 0...n
    if a[i][1] == 1
        left2 += 1
    end
end
left = left1 + left2
if left1 == n - left2 && left1 == n
    puts 0
elsif left1 == n - left2 && left1 == 0
    puts 0
elsif

    if left >= 2*n - left
        puts 2*n - left
    else
        puts left
    end
end

#file_contents = File.read('test.in')
numbers = gets.scan(/\d+/)
numbers.collect! &:to_i

n = numbers.shift
left_count = right_count = 0
numbers.each_index {|index|
  if index.even?
    left_count += numbers[index]
  else
    right_count += numbers[index]
  end
}
puts [left_count, n - left_count].min + [right_count, n - right_count].min

numbers = gets.chomp.scan(/\d+/)
numbers.collect! &:to_i

n = numbers.shift
left_count = right_count = 0
numbers.each_index {|index|
  if index.even?
    left_count += numbers[index]
  else
    right_count += numbers[index]
  end
}
puts [left_count, n - left_count].min + [right_count, n - right_count].min


IT City administration has no rest because of the fame of the Pyramids in Egypt. There is a project of construction of pyramid complex near the city in the place called Emerald Walley. The distinction of the complex is that its pyramids will be not only quadrangular as in Egypt but also triangular and pentagonal. Of course the amount of the city budget funds for the construction depends on the pyramids' volume. Your task is to calculate the volume of the pilot project consisting of three pyramids — one triangular, one quadrangular and one pentagonal.The first pyramid has equilateral triangle as its base, and all 6 edges of the pyramid have equal length. The second pyramid has a square as its base and all 8 edges of the pyramid have equal length. The third pyramid has a regular pentagon as its base and all 10 edges of the pyramid have equal length.

The only line of the input contains three integers l3, l4, l5 (1 ≤ l3, l4, l5 ≤ 1000) — the edge lengths of triangular, quadrangular and pentagonal pyramids correspondingly.

Output one number — the total volume of the pyramids. Absolute or relative error should not be greater than 10 - 9.


Kris works in a large company "Blake Technologies". As a best engineer of the company he was assigned a task to develop a printer that will be able to print horizontal and vertical strips. First prototype is already built and Kris wants to tests it. He wants you to implement the program that checks the result of the printing.Printer works with a rectangular sheet of paper of size n × m. Consider the list as a table consisting of n rows and m columns. Rows are numbered from top to bottom with integers from 1 to n, while columns are numbered from left to right with integers from 1 to m. Initially, all cells are painted in color 0.Your program has to support two operations:   Paint all cells in row ri in color ai;  Paint all cells in column ci in color ai. If during some operation i there is a cell that have already been painted, the color of this cell also changes to ai.Your program has to print the resulting table after k operation.

The first line of the input contains three integers n, m and k (1  ≤  n,  m  ≤ 5000, n·m ≤ 100 000, 1 ≤ k ≤ 100 000) — the dimensions of the sheet and the number of operations, respectively. Each of the next k lines contains the description of exactly one query:    1 ri ai (1 ≤ ri ≤ n, 1 ≤ ai ≤ 109), means that row ri is painted in color ai;  2 ci ai (1 ≤ ci ≤ m, 1 ≤ ai ≤ 109), means that column ci is painted in color ai.

Print n lines containing m integers each — the resulting table after all operations are applied.

NoteThe figure below shows all three operations for the first sample step by step. The cells that were painted on the corresponding step are marked gray.

buf = gets.split(' ');
n, m, k = buf[0].to_i, buf[1].to_i, buf[2].to_i
len = 5555
r = Array.new(len, 0)
c = Array.new(len, 0)
rid = Array.new(len, 0)
cid = Array.new(len, 0)
for i in 1..k
	buf = gets.split(' ');
	op, x, v = buf[0].to_i, buf[1].to_i, buf[2].to_i
	if op==1
		r[x]=v
		rid[x]=i
	else
		c[x]=v
		cid[x]=i
	end
end
for i in 1..n
	for j in 1..m
		val=0
		if rid[i]>cid[j] then val=r[i]
		else val=c[j]
		end
		print val
		if j<m then print ' '
		else puts
		end
	end
end


Stepan had a favorite string s which consisted of the lowercase letters of the Latin alphabet. After graduation, he decided to remember it, but it was a long time ago, so he can't now remember it. But Stepan remembers some information about the string, namely the sequence of integers c1, c2, ..., cn, where n equals the length of the string s, and ci equals the number of substrings in the string s with the length i, consisting of the same letters. The substring is a sequence of consecutive characters in the string s.For example, if the Stepan's favorite string is equal to "tttesst", the sequence c looks like: c = [7, 3, 1, 0, 0, 0, 0].Stepan asks you to help to repair his favorite string s according to the given sequence c1, c2, ..., cn.

The first line contains the integer n (1 ≤ n ≤ 2000) — the length of the Stepan's favorite string. The second line contains the sequence of integers c1, c2, ..., cn (0 ≤ ci ≤ 2000), where ci equals the number of substrings of the string s with the length i, consisting of the same letters. It is guaranteed that the input data is such that the answer always exists.

Print the repaired Stepan's favorite string. If there are several answers, it is allowed to print any of them. The string should contain only lowercase letters of the English alphabet.

NoteIn the first test Stepan's favorite string, for example, can be the string "kkrrrq", because it contains 6 substrings with the length 1, consisting of identical letters (they begin in positions 1, 2, 3, 4, 5 and 6), 3 substrings with the length 2, consisting of identical letters (they begin in positions 1, 3 and 4), and 1 substring with the length 3, consisting of identical letters (it begins in the position 3).

rd = -> {gets.split.map &:to_i}
n, = rd[]
a = rd[]
l = 0
i = n - 1
while i >= 0
	if a[i] == 0
		i -= 1
		next
	end
	j = 0
	while j < a[i]
		c = (97 + l % 26).chr
		l += 1
		for k in (0..i)
			print c
		end
		j += 1
	end
	j = i - 1
	while j >= 0
		a[j] -= (i - j + 1) * a[i]
		j -= 1
	end
	i -= 1
end
puts


You are given a positive integer $$$n$$$.The weight of a permutation $$$p_1, p_2, \ldots, p_n$$$ is the number of indices $$$1\le i\le n$$$ such that $$$i$$$ divides $$$p_i$$$. Find a permutation $$$p_1,p_2,\dots, p_n$$$ with the minimum possible weight (among all permutations of length $$$n$$$).A permutation is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2,3,1,5,4]$$$ is a permutation, but $$$[1,2,2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1,3,4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array).

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \leq t \leq 10^4$$$). The description of the test cases follows. The only line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 10^5$$$) — the length of permutation. It is guaranteed that the sum of $$$n$$$ over all test cases does not exceed $$$10^5$$$.

For each test case, print a line containing $$$n$$$ integers $$$p_1, p_2,\dots, p_n$$$ so that the permutation $$$p$$$ has the minimum possible weight. If there are several possible answers, you can print any of them.

NoteIn the first test case, the only valid permutation is $$$p=[1]$$$. Its weight is $$$1$$$.In the second test case, one possible answer is the permutation $$$p=[2,1,4,3]$$$. One can check that $$$1$$$ divides $$$p_1$$$ and $$$i$$$ does not divide $$$p_i$$$ for $$$i=2,3,4$$$, so the weight of this permutation is $$$1$$$. It is impossible to find a permutation of length $$$4$$$ with a strictly smaller weight.

lines = gets.chomp.to_i
lines.times do
    input = (1..gets.chomp.to_i).to_a
    for i in (0..input.size-2).step 2 do
       aux = input[i]
       input[i] = input[i+1]
       input[i+1] = aux
    end
    if input.size % 2 == 1 and input.size > 1
        aux = input[-1]
        input[-1] = input[-2]
        input[-2] = aux
    end
    puts input * " "
end

def main
  t = inp.to_i
  t.times do
    n = inp.to_i
    if n & 1 == 0
      1.upto(n) do |i|
        print (i & 1 == 0)? (i - 1) : (i + 1)
        print " " if i != n
      end
    else
      print 1
      2.upto(n) do |i|
        print " "
        print (i & 1 == 0)? (i + 1) : (i - 1)
      end
    end
    puts ""

  end

end

# lib
def inp
  gets.chomp
end

def inarr
  gets.chomp.split
end

def mapint(lst)
  lst.map(&:to_i)
end

def max(a, b)
  (a > b)? a:b
end

def min(a, b)
  (a < b)? a:b
end

main

lines = gets.chomp.to_i
lines.times do
    input = (1..gets.chomp.to_i).to_a
    for i in (0..input.size-2).step 2 do
       aux = input[i]
       input[i] = input[i+1]
       input[i+1] = aux
    end
    if input.size % 2 == 1 and input.size > 1
        aux = input[-1]
        input[-1] = input[-2]
        input[-2] = aux
    end
    puts input * ""
end


Burenka and Tonya are playing an old Buryat game with a chip on a board of $$$n \times m$$$ cells.At the beginning of the game, the chip is located in the lower left corner of the board. In one move, the player can move the chip to the right or up by any odd number of cells (but you cannot move the chip both to the right and up in one move). The one who cannot make a move loses.Burenka makes the first move, the players take turns. Burenka really wants to win the game, but she is too lazy to come up with a strategy, so you are invited to solve the difficult task of finding it. Name the winner of the game (it is believed that Burenka and Tonya are masters of playing with chips, so they always move in the optimal way).    Chip's starting cell is green, the only cell from which chip can't move is red. if the chip is in the yellow cell, then blue cells are all options to move the chip in one move.

The first line contains one integer $$$t$$$ ($$$1 \leq t \leq 10^4$$$) — the number of test cases. The following is a description of the input data sets. The only line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n, m \leq 10^9$$$) — the dimensions of the game board.

For each test case print a single line — the name of the winner of the game ("Burenka" or "Tonya").

Tonya
Burenka
Burenka
Tonya
Burenka
Burenka

NoteIn the first case, Burenka has no move, so Tonya wins.In the second case, Burenka can move $$$3$$$ cells to the right, after which Tony will not be able to make a move, which means that Burenka wins.In the third case, Burenka can move $$$5$$$ squares to the right. Then we can say that we have a game on a board of $$$1 \times 5$$$ cells, and Tonya is the first player. In such game the second player wins, so in the original one Burenka will win.

def main
  t = inp.to_i
  t.times do
    n, m = mapint(inarr)
    if n % 2 == 0
      puts (m % 2 == 0)? "Tonya": "Burenka"
    else
      puts (m % 2 == 1)? "Tonya": "Burenka"
    end

  end
end

# lib
def inp
  gets.chomp
end

def inarr
  gets.chomp.split
end

def mapint(lst)
  lst.map(&:to_i)
end

def max(a, b)
  (a > b)? a:b
end

def min(a, b)
  (a < b)? a:b
end

main

gets.to_i.times do
  n, m = gets.split.map(&:to_i)
  go = ->x { x -= 1; x == 0 ? 0 : x % 2 == 1 ? 1 : 2 }
  steps = go[n] + go[m]
  puts steps % 2 == 0 ? "Tonya" : "Burenka"
end


Even if it's a really easy question, she won't be able to answer it— Perfect Memento in Strict SenseCirno's perfect bitmasks classroom has just started!Cirno gave her students a positive integer $$$x$$$. As an assignment, her students need to find the minimum positive integer $$$y$$$, which satisfies the following two conditions:$$$$$$x\ \texttt{and}\ y > 0$$$$$$ $$$$$$x\ \texttt{xor}\ y > 0$$$$$$Where $$$\texttt{and}$$$ is the bitwise AND operation, and $$$\texttt{xor}$$$ is the bitwise XOR operation.Among the students was Mystia, who was truly baffled by all these new operators. Please help her!

The first line of input contains a single integer $$$t$$$ ($$$1 \leq t \leq 10^3$$$) — the number of input test cases. For each test case, the only line of input contains one integer $$$x$$$ ($$$1 \leq x \leq 2^{30}$$$).

For each test case, print a single integer — the minimum number of $$$y$$$.

gets.to_i.times do
  x = gets.to_i
  start = 1 << x.to_s(2).reverse.index("1")
  p (start..).find { |y| x & y > 0 && x ^ y > 0 }
end

gets.to_i.times do
    n=gets.to_i
    if n==1
        puts 3
    elsif n%2==1
        puts 1
    else
        t=n
        while t%2==0 do
            t/=2
        end
        if t==1
            puts n+1
        else
            puts n/t
        end
    end
end


It is winter now, and Max decided it's about time he watered the garden.The garden can be represented as n consecutive garden beds, numbered from 1 to n. k beds contain water taps (i-th tap is located in the bed xi), which, if turned on, start delivering water to neighbouring beds. If the tap on the bed xi is turned on, then after one second has passed, the bed xi will be watered; after two seconds have passed, the beds from the segment [xi - 1, xi + 1] will be watered (if they exist); after j seconds have passed (j is an integer number), the beds from the segment [xi - (j - 1), xi + (j - 1)] will be watered (if they exist). Nothing changes during the seconds, so, for example, we can't say that the segment [xi - 2.5, xi + 2.5] will be watered after 2.5 seconds have passed; only the segment [xi - 2, xi + 2] will be watered at that moment.  The garden from test 1. White colour denotes a garden bed without a tap, red colour — a garden bed with a tap.   The garden from test 1 after 2 seconds have passed after turning on the tap. White colour denotes an unwatered garden bed, blue colour — a watered bed. Max wants to turn on all the water taps at the same moment, and now he wonders, what is the minimum number of seconds that have to pass after he turns on some taps until the whole garden is watered. Help him to find the answer!

The first line contains one integer t — the number of test cases to solve (1 ≤ t ≤ 200). Then t test cases follow. The first line of each test case contains two integers n and k (1 ≤ n ≤ 200, 1 ≤ k ≤ n) — the number of garden beds and water taps, respectively. Next line contains k integers xi (1 ≤ xi ≤ n) — the location of i-th water tap. It is guaranteed that for each  condition xi - 1 < xi holds. It is guaranteed that the sum of n over all test cases doesn't exceed 200. Note that in hacks you have to set t = 1.

For each test case print one integer — the minimum number of seconds that have to pass after Max turns on some of the water taps, until the whole garden is watered.

NoteThe first example consists of 3 tests:  There are 5 garden beds, and a water tap in the bed 3. If we turn it on, then after 1 second passes, only bed 3 will be watered; after 2 seconds pass, beds [1, 3] will be watered, and after 3 seconds pass, everything will be watered.  There are 3 garden beds, and there is a water tap in each one. If we turn all of them on, then everything will be watered after 1 second passes.  There are 4 garden beds, and only one tap in the bed 1. It will take 4 seconds to water, for example, bed 4.

t = gets.chomp.to_i
t.times do
  beds = gets.chomp.split(' ').map{|x| x.to_i}[0]
  taplist = gets.chomp.split(' ').map{|x| x.to_i - 1}
  taplist = [-1] + taplist + [beds]

  longest = 0
  (0..taplist.size-2).each do |i|
    time = 0
    if i == 0 then
      time = taplist[i+1] - taplist[0]
      # puts "time between #{taplist[0]} and #{taplist[i+1]} is #{time}"
    elsif i == taplist.size-2 then
      time = taplist[-1] - taplist[i]
      # puts "time between #{taplist[-1]} and #{taplist[i]} is #{time}"

    else
      if (taplist[i+1] - taplist[i]) == 1
        time = 1
      else
        time = (taplist[i+1] - taplist[i])/2 + 1
      end
      # puts "time between #{taplist[i+1]} and #{taplist[i]} is #{time}"

    end

    longest = time if time > longest
  end
  puts longest
end

gets.to_i.times{
	n,k=gets.split.map &:to_i
	a=gets.split.map &:to_i
	p [a[0],n+1-a[-1],*a.each_cons(2).map{|x,y|(y-x+2)/2}].max
}

def solve
  n, k = gets.strip.split.map(&:to_i)
  a = gets.strip.split.map(&:to_i)
  mx = [a.first, n - a.last + 1].max
  (1...(a.size)).each do |i|
    mx = [mx, ((a[i] - a[i-1] - 1) / 2.0).ceil + 1].max
  end
  mx
end

gets.strip.to_i.times do
  puts solve
end

gets.to_i.times do
  n, m = gets.split.map(&:to_i)
  a = gets.chomp.split.map(&:to_i)
  ans = 0
  (1..n).each do |i|
    tmp = 300
    a.each do |j|
      tmp = [tmp, (i-j).abs + 1].min
    end
    ans = [ans, tmp].max
  end
  puts ans
end

inp = gets.chomp.to_i
otv = []

inp.times{ |w|
count = 0
map = []

row = gets.chomp.split(" ")
gryadok = row[0]

(0..gryadok.to_i-1).each {|w| map[w] = 0}

crans = gets.chomp.split(" ")

startup = []
startdown = []

crans.size.times{|e|
startup[e] = crans[e].to_i-1
startdown[e] = crans[e].to_i-1
}

loop do

crans.size.times{|e|

map[startup[e]] = 1
map[startdown[e]] = 1
if startup[e] > 0
startup[e]-=1
end
if startdown[e] < (gryadok.to_i-1)
startdown[e]+=1
end

}

#puts map.to_s

count+=1
if map.index(0).nil? then otv.push(count);break; end

end

}

otv.size.times{|w|
puts otv[w]
}

def solve n, xs
  xs.sort!
  ans = [1, xs[0], n+1-xs[xs.size-1]].max
  (xs.size - 1).times do |i|
    ans = [ans, (xs[i+1] - xs[i] + 2)/ 2].max
  end
  p ans
end

q = gets.to_i
q.times do
  n, m = gets.chomp.split.map(&:to_i)
  xs = gets.chomp.split.map(&:to_i)
  solve n, xs
end

t = gets.chomp.to_i
t.times do
  beds = gets.chomp.split(' ').map{|x| x.to_i}[0]
  taplist = gets.chomp.split(' ').map{|x| x.to_i - 1}
  taplist = [-1] + taplist + [beds]

  longest = 0
  (0..taplist.size-2).each do |i|
    time = 0
    if i == 0 then
      time = taplist[i+1] - taplist[0] + 1
    elsif i == taplist.size-2 then
      time = taplist[-1] - taplist[i] + 1
    else
      time = (taplist[i+1] - taplist[i])/2
    end

    longest = time if time > longest
  end
  puts longest - 1
end

gets.to_i.times{
	n,k=gets.split.map &:to_i
	a=gets.split.map &:to_i
	p [n+1-a[-1],*a.each_cons(2).map{|x,y|(y-x+2)/2}].max
}

def solve
  n, k = gets.strip.split.map(&:to_i)
  a = gets.strip.split.map(&:to_i)
  mx = [a.first, n - a.last + 1].max
  (1...(a.size)).each do |i|
    mx = [mx, ((a[i] - a[i-1] - 1) / 2).ceil + 1].max
  end
  mx
end

gets.strip.to_i.times do
  puts solve
end

inp = gets.chomp.to_i
otv = []

inp.times{ |w|
count = 0

row = gets.chomp.split(" ")
gryadok = row[0]

crans = gets.chomp.split(" ")
crans.each{|w| count+=w.to_i}

if (gryadok.to_i - count.to_i) < 0

otv.push(1)

else

otv.push(gryadok.to_i - count.to_i + 1)

end

}

otv.size.times{ |w|
puts otv[w]
}

def solve n, xs
  xs.sort!
  ans = [1, xs[0], n+1-xs[xs.size-1]].max
  (xs.size - 1).times do |i|
    ans = [ans, (xs[i+1] - xs[i] + 1)/ 2].max
  end
  p ans
end

q = gets.to_i
q.times do
  n, m = gets.chomp.split.map(&:to_i)
  xs = gets.chomp.split.map(&:to_i)
  solve n, xs
end


You are given an array $$$a$$$ consisting of $$$n$$$ integers (it is guaranteed that $$$n$$$ is even, i.e. divisible by $$$2$$$). All $$$a_i$$$ does not exceed some integer $$$k$$$.Your task is to replace the minimum number of elements (replacement is the following operation: choose some index $$$i$$$ from $$$1$$$ to $$$n$$$ and replace $$$a_i$$$ with some integer in range $$$[1; k]$$$) to satisfy the following conditions:  after all replacements, all $$$a_i$$$ are positive integers not greater than $$$k$$$;  for all $$$i$$$ from $$$1$$$ to $$$\frac{n}{2}$$$ the following equation is true: $$$a_i + a_{n - i + 1} = x$$$, where $$$x$$$ should be the same for all $$$\frac{n}{2}$$$ pairs of elements. You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 2 \cdot 10^5, 1 \le k \le 2 \cdot 10^5$$$) — the length of $$$a$$$ and the maximum possible value of some $$$a_i$$$ correspondingly. It is guratanteed that $$$n$$$ is even (i.e. divisible by $$$2$$$). The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le k$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. It is guaranteed that the sum of $$$n$$$ (as well as the sum of $$$k$$$) over all test cases does not exceed $$$2 \cdot 10^5$$$ ($$$\sum n \le 2 \cdot 10^5$$$, $$$\sum k \le 2 \cdot 10^5$$$).

For each test case, print the answer — the minimum number of elements you have to replace in $$$a$$$ to satisfy the conditions from the problem statement.


There are $$$n$$$ segments $$$[l_i, r_i]$$$ for $$$1 \le i \le n$$$. You should divide all segments into two non-empty groups in such way that there is no pair of segments from different groups which have at least one common point, or say that it's impossible to do it. Each segment should belong to exactly one group.To optimize testing process you will be given multitest.

The first line contains one integer $$$T$$$ ($$$1 \le T \le 50000$$$) — the number of queries. Each query contains description of the set of segments. Queries are independent. First line of each query contains single integer $$$n$$$ ($$$2 \le n \le 10^5$$$) — number of segments. It is guaranteed that $$$\sum{n}$$$ over all queries does not exceed $$$10^5$$$. The next $$$n$$$ lines contains two integers $$$l_i$$$, $$$r_i$$$ per line ($$$1 \le l_i \le r_i \le 2 \cdot 10^5$$$) — the $$$i$$$-th segment.

For each query print $$$n$$$ integers $$$t_1, t_2, \dots, t_n$$$ ($$$t_i \in \{1, 2\}$$$) — for each segment (in the same order as in the input) $$$t_i$$$ equals $$$1$$$ if the $$$i$$$-th segment will belongs to the first group and $$$2$$$ otherwise. If there are multiple answers, you can print any of them. If there is no answer, print $$$-1$$$.

NoteIn the first query the first and the second segments should be in different groups, but exact numbers don't matter.In the second query the third segment intersects with the first and the second segments, so they should be in the same group, but then the other group becomes empty, so answer is $$$-1$$$.In the third query we can distribute segments in any way that makes groups non-empty, so any answer of $$$6$$$ possible is correct.

DBG = true
t = gets.to_i
for i in 0...t
  n = gets.to_i
  lr = []
  for j in 0...n
    ll,rr = gets.split.map{|z| z.to_i}
    lr << [ll,rr]
  end
  slr = lr.sort_by{|x| x[0]}
  rmax = slr[0][1]
  bdr = -1
  for j in 1...n
    if rmax < slr[j][0]
      bdr = rmax
      break
    end
    rmax = [rmax, slr[j][1]].max
  end
  if bdr == -1
    puts "-1"
  else
    for j in 0...n
      if lr[j][0] <= bdr
        print "1 "
      else
        print "2 "
      end
    end
    puts ""
  end
end

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

t = gets.to_i

t.times do
  n = gets.to_i
  arr = []

  (0..n-1).each do |i|
    arr.push gets.chomp.split(" ").map(&:to_i)+[i]
  end

#  p arr

  arr.sort_by!{|x| [x[0],x[1]]}

#  p arr

  newarr = []

  z = 1

=begin
  done = false
  arr.each_with_index do |x,i|
  	if i+2<n and x[1]>=arr[i+2][0]
  		puts -1
  		done = true
  		break
  	end
  	newarr.push (x+[z])
  	if i<n-1 and not x[1]>=arr[i+1][0]
	  	z = 3-z
	end
  end
=end

  hasone = false
  hastwo = false

  maxtillnow = -1.0/0.0

  arr.each_with_index do |x,i|
    newarr.push (x+[z])
    if z==1
    	hasone = true
    else
    	hastwo = true
    end
    maxtillnow = x[1] if x[1]>maxtillnow
  	if i+1<n and maxtillnow<arr[i+1][0]
#  		good = true
	  	z = 3-z
	end
  end

#  next if done

#  p newarr
  newarr.sort_by!{|x| x[2]}
#  p newarr
#  p hasone
#  p hastwo

  if not (hasone and hastwo)
  	puts -1
  	next
  end

  newarr.each do |x|
  	print x[3]
  	print " "
  end
  puts
end

DBG = true
t = gets.to_i
for i in 0...t
  n = gets.to_i
  l = []
  r = []
  for i in 0...n
    a,b = gets.split.map{|z| z.to_i}
    l << a
    r << b
  end
  ll = l.sort!
  rr = r.sort!
  lmax = ll[-1]
  rmin = rr[0]
  if lmax <= rmin
    puts "-1"
    next
  end
  for i in 0...n
    if r[i] < lmax
      print "1 "
    else
      print "2 "
    end
  end
  puts ""
end

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

t = gets.to_i

t.times do
  n = gets.to_i
  arr = []

  (0..n-1).each do |i|
    arr.push gets.chomp.split(" ").map(&:to_i)+[i]
  end

  arr.sort_by{|x| [x[0],x[1]]}

  newarr = []

  z = 1
  done = false
  arr.each_with_index do |x,i|
  	if i+2<n and x[1]>=arr[i+2][0]
  		puts -1
  		done = true
  		break
  	end
  	newarr.push (x+[z])
  	z = 3-z
  end

  next if done

  newarr.sort_by{|x| x[2]}
  newarr.each do |x|
  	print x[3]
  	print " "
  end
  puts
end

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

t = gets.to_i

t.times do
  n = gets.to_i
  arr = []

  (0..n-1).each do |i|
    arr.push gets.chomp.split(" ").map(&:to_i)+[i]
  end

#  p arr

  arr.sort_by!{|x| [x[0],x[1]]}

#  p arr

  newarr = []

  z = 1

=begin
  done = false
  arr.each_with_index do |x,i|
  	if i+2<n and x[1]>=arr[i+2][0]
  		puts -1
  		done = true
  		break
  	end
  	newarr.push (x+[z])
  	if i<n-1 and not x[1]>=arr[i+1][0]
	  	z = 3-z
	end
  end
=end

  arr.each_with_index do |x,i|
    newarr.push (x+[z])
  	if i<n-1 and not x[1]>=arr[i+1][0]
#  		good = true
	  	z = 3-z
	end
  end

#  next if done

#  p newarr
  newarr.sort_by!{|x| x[2]}
#  p newarr

  hasone = false
  hastwo = false
  newarr.each do |x|
  	if x[3]==1
  		hasone = true
  	else
  		hastwo = true
  	end
  	if hasone and hastwo
  		break
  	end
  end

#  p hasone
#  p hastwo

  if not (hasone and hastwo)
  	puts -1
  	next
  end

  newarr.each do |x|
  	print x[3]
  	print " "
  end
  puts
end

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

t = gets.to_i

t.times do
  n = gets.to_i
  arr = []

  (0..n-1).each do |i|
    arr.push gets.chomp.split(" ").map(&:to_i)+[i]
  end

#  p arr

  arr.sort_by!{|x| [x[0],x[1]]}

#  p arr

  newarr = []

  z = 1

=begin
  done = false
  arr.each_with_index do |x,i|
  	if i+2<n and x[1]>=arr[i+2][0]
  		puts -1
  		done = true
  		break
  	end
  	newarr.push (x+[z])
  	if i<n-1 and not x[1]>=arr[i+1][0]
	  	z = 3-z
	end
  end
=end

  arr.each_with_index do |x,i|
    newarr.push (x+[z])
  	if i<n-1 and not x[1]>=arr[i+1][0]
	  	z = 3-z
	end
  end

#  next if done

#  p newarr
  newarr.sort_by!{|x| x[2]}
#  p newarr

  hasone = false
  hastwo = false
  newarr.each do |x|
  	if x[3]==1
  		hasone = true
  	else
  		hastwo = true
  	end
  	if hasone and hastwo
  		break
  	end
  end

#  p hasone
#  p hastwo

  if not (hasone and hastwo)
  	puts -1
  	next
  end

  newarr.each do |x|
  	print x[3]
  	print " "
  end
  puts
end

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

t = gets.to_i

t.times do
  n = gets.to_i
  arr = []

  (0..n-1).each do |i|
    arr.push gets.chomp.split(" ").map(&:to_i)+[i]
  end

#  p arr

  arr.sort_by!{|x| [x[0],x[1]]}

#  p arr

  newarr = []

  z = 1
  done = false
  arr.each_with_index do |x,i|
  	if i+2<n and x[1]>=arr[i+2][0]
  		puts -1
  		done = true
  		break
  	end
  	newarr.push (x+[z])
  	z = 3-z
  end

  next if done

  newarr.sort_by!{|x| x[2]}
  newarr.each do |x|
  	print x[3]
  	print " "
  end
  puts
end

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

t = gets.to_i

t.times do
  n = gets.to_i
  arr = []

  (0..n-1).each do |i|
    arr.push gets.chomp.split(" ").map(&:to_i)+[i]
  end

  arr.sort_by{|x| [x[0],x[1]]}

  newarr = []

  z = 1
  done = false
  arr.each_with_index do |x,i|
  	if i+2<n and x[1]>arr[i+2][0]
  		puts -1
  		done = true
  		break
  	end
  	newarr.push (x+[z])
  	z = 3-z
  end

  next if done

  newarr.sort_by{|x| x[2]}
  newarr.each do |x|
  	print x[3]
  	print " "
  end
  puts
end


There is a grid with $$$n$$$ rows and $$$m$$$ columns. Some cells are colored black, and the rest of the cells are colored white.In one operation, you can select some black cell and do exactly one of the following:   color all cells in its row black, or  color all cells in its column black. You are given two integers $$$r$$$ and $$$c$$$. Find the minimum number of operations required to make the cell in row $$$r$$$ and column $$$c$$$ black, or determine that it is impossible.

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains four integers $$$n$$$, $$$m$$$, $$$r$$$, and $$$c$$$ ($$$1 \leq n, m \leq 50$$$; $$$1 \leq r \leq n$$$; $$$1 \leq c \leq m$$$) — the number of rows and the number of columns in the grid, and the row and column of the cell you need to turn black, respectively. Then $$$n$$$ lines follow, each containing $$$m$$$ characters. Each of these characters is either 'B' or 'W' — a black and a white cell, respectively.

For each test case, if it is impossible to make the cell in row $$$r$$$ and column $$$c$$$ black, output $$$-1$$$.  Otherwise, output a single integer — the minimum number of operations required to make the cell in row $$$r$$$ and column $$$c$$$ black.

9

3 5 1 4

WBWWW

BBBWB

WWBBB

4 3 2 1

BWW

BBW

WBB

WWB

2 3 2 2

WWW

WWW

2 2 1 1

WW

WB

5 9 5 9

WWWWWWWWW

WBWBWBBBW

WBBBWWBWW

WBWBWBBBW

WWWWWWWWW

1 1 1 1

B

1 1 1 1

W

1 2 1 1

WB

2 1 1 1

W

B

NoteThe first test case is pictured below.  We can take the black cell in row $$$1$$$ and column $$$2$$$, and make all cells in its row black. Therefore, the cell in row $$$1$$$ and column $$$4$$$ will become black.  In the second test case, the cell in row $$$2$$$ and column $$$1$$$ is already black.In the third test case, it is impossible to make the cell in row $$$2$$$ and column $$$2$$$ black.The fourth test case is pictured below.  We can take the black cell in row $$$2$$$ and column $$$2$$$ and make its column black.   Then, we can take the black cell in row $$$1$$$ and column $$$2$$$ and make its row black.   Therefore, the cell in row $$$1$$$ and column $$$1$$$ will become black.

gets.to_i.times do
  n, m, r, c = gets.split.map(&:to_i)
  grid = n.times.map { gets.chomp }
  if grid[r - 1][c - 1] == "B"
    p 0
  elsif grid[r - 1].include?("B") || grid.any? { |row| row[c - 1] == "B" }
    p 1
  elsif grid.any? { |row| row.include?("B") }
    p 2
  else
    p -1
  end
end


There are $$$n$$$ children numbered from $$$1$$$ to $$$n$$$ in a kindergarten. Kindergarten teacher gave $$$a_i$$$ ($$$1 \leq a_i \leq n$$$) candies to the $$$i$$$-th child. Children were seated in a row in order from $$$1$$$ to $$$n$$$ from left to right and started eating candies. While the $$$i$$$-th child was eating candies, he calculated two numbers $$$l_i$$$ and $$$r_i$$$ — the number of children seating to the left of him that got more candies than he and the number of children seating to the right of him that got more candies than he, respectively.Formally, $$$l_i$$$ is the number of indices $$$j$$$ ($$$1 \leq j < i$$$), such that $$$a_i < a_j$$$ and $$$r_i$$$ is the number of indices $$$j$$$ ($$$i < j \leq n$$$), such that $$$a_i < a_j$$$.Each child told to the kindergarten teacher the numbers $$$l_i$$$ and $$$r_i$$$ that he calculated. Unfortunately, she forgot how many candies she has given to each child. So, she asks you for help: given the arrays $$$l$$$ and $$$r$$$ determine whether she could have given the candies to the children such that all children correctly calculated their values $$$l_i$$$ and $$$r_i$$$, or some of them have definitely made a mistake. If it was possible, find any way how she could have done it.

On the first line there is a single integer $$$n$$$ ($$$1 \leq n \leq 1000$$$) — the number of children in the kindergarten. On the next line there are $$$n$$$ integers $$$l_1, l_2, \ldots, l_n$$$ ($$$0 \leq l_i \leq n$$$), separated by spaces. On the next line, there are $$$n$$$ integer numbers $$$r_1, r_2, \ldots, r_n$$$ ($$$0 \leq r_i \leq n$$$), separated by spaces.

If there is no way to distribute the candies to the children so that all of them calculated their numbers correctly, print «NO» (without quotes). Otherwise, print «YES» (without quotes) on the first line. On the next line, print $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$, separated by spaces — the numbers of candies the children $$$1, 2, \ldots, n$$$ received, respectively. Note that some of these numbers can be equal, but all numbers should satisfy the condition $$$1 \leq a_i \leq n$$$. The number of children seating to the left of the $$$i$$$-th child that got more candies than he should be equal to $$$l_i$$$ and the number of children seating to the right of the $$$i$$$-th child that got more candies than he should be equal to $$$r_i$$$. If there is more than one solution, find any of them.

NoteIn the first example, if the teacher distributed $$$1$$$, $$$3$$$, $$$1$$$, $$$2$$$, $$$1$$$ candies to $$$1$$$-st, $$$2$$$-nd, $$$3$$$-rd, $$$4$$$-th, $$$5$$$-th child, respectively, then all the values calculated by the children are correct. For example, the $$$5$$$-th child was given $$$1$$$ candy, to the left of him $$$2$$$ children were given $$$1$$$ candy, $$$1$$$ child was given $$$2$$$ candies and $$$1$$$ child — $$$3$$$ candies, so there are $$$2$$$ children to the left of him that were given more candies than him.In the second example it is impossible to distribute the candies, because the $$$4$$$-th child made a mistake in calculating the value of $$$r_4$$$, because there are no children to the right of him, so $$$r_4$$$ should be equal to $$$0$$$.In the last example all children may have got the same number of candies, that's why all the numbers are $$$0$$$. Note that each child should receive at least one candy.

require 'set'
n = gets.to_i

class KG

  def initialize(ind,l,r)
    @ind = ind
    @l = l
    @r = r
  end

  attr_accessor :ind
  attr_accessor :l
  attr_accessor :r
  attr_accessor :val
end

ls = gets.chomp.split(" ").map(&:to_i)
rs = gets.chomp.split(" ").map(&:to_i)

students = []
(0..n-1).each do |i|
  students.push KG.new(i,ls[i],rs[i])
end

newstud = []

students.each_with_index do |student,i|

  if student.l>i
    puts "NO"
    exit
  end
  newstud.insert(student.l,student)
end

val = n

newstud.each_with_index do |stud,i|
  students[stud.ind].val = val

  unless ((i!=(n-1)) and stud.l+stud.r == newstud[i+1].l+newstud[i+1].r)
    val-=1
  end
end

seen = Array.new

students.reverse.each do |stud|
  k = 0
  seen.each do |seenstud|
    k+=1 if seenstud>stud.val
  end

  if k!=stud.r
    puts "NO"
    exit
  end

  seen.push stud.val
end

puts "YES"
students.each do |stud|
  print "#{stud.val} "
end
puts

require 'set'
n = gets.to_i

class KG

  def initialize(ind,l,r)
    @ind = ind
    @l = l
    @r = r
  end

  attr_accessor :ind
  attr_accessor :l
  attr_accessor :r
  attr_accessor :val
end

ls = gets.chomp.split(" ").map(&:to_i)
rs = gets.chomp.split(" ").map(&:to_i)

students = []
(0..n-1).each do |i|
  students.push KG.new(i,ls[i],rs[i])
end

newstud = []

students.each_with_index do |student,i|

  if student.l>i
    puts "NO"
    exit
  end
  newstud.insert(student.l,student)
end

val = n

newstud.each_with_index do |stud,i|
  students[stud.ind].val = val

  unless ((i!=(n-1)) and stud.l+stud.r == newstud[i+1].l+newstud[i+1].r)
    val-=1
  end
end

#students.each do |stud|
#  puts "#{stud.ind} #{stud.val} #{stud.l} #{stud.r}"
#end

seen = Set.new

students.reverse.each do |stud|
  k = 0
  seen.each do |seenstud|
    k+=1 if seenstud>stud.val
  end

  if k!=stud.r
    puts "NO"
    exit
  end

  seen.add stud.val
end

puts "YES"
students.each do |stud|
  print "#{stud.val} "
end
puts


A boy Petya loves chess very much. He even came up with a chess piece of his own, a semiknight. The semiknight can move in any of these four directions: 2 squares forward and 2 squares to the right, 2 squares forward and 2 squares to the left, 2 squares backward and 2 to the right and 2 squares backward and 2 to the left. Naturally, the semiknight cannot move beyond the limits of the chessboard.Petya put two semiknights on a standard chessboard. Petya simultaneously moves with both semiknights. The squares are rather large, so after some move the semiknights can meet, that is, they can end up in the same square. After the meeting the semiknights can move on, so it is possible that they meet again. Petya wonders if there is such sequence of moves when the semiknights meet. Petya considers some squares bad. That is, they do not suit for the meeting. The semiknights can move through these squares but their meetings in these squares don't count.Petya prepared multiple chess boards. Help Petya find out whether the semiknights can meet on some good square for each board.Please see the test case analysis.

The first line contains number t (1 ≤ t ≤ 50) — the number of boards. Each board is described by a matrix of characters, consisting of 8 rows and 8 columns. The matrix consists of characters ".", "#", "K", representing an empty good square, a bad square and the semiknight's position, correspondingly. It is guaranteed that matrix contains exactly 2 semiknights. The semiknight's squares are considered good for the meeting. The tests are separated by empty line.

For each test, print on a single line the answer to the problem: "YES", if the semiknights can meet and "NO" otherwise.

NoteConsider the first board from the sample. We will assume the rows and columns of the matrix to be numbered 1 through 8 from top to bottom and from left to right, correspondingly. The knights can meet, for example, in square (2, 7). The semiknight from square (4, 1) goes to square (2, 3) and the semiknight goes from square (8, 1) to square (6, 3). Then both semiknights go to (4, 5) but this square is bad, so they move together to square (2, 7).On the second board the semiknights will never meet.

t = gets.to_i
for i in 0...t
	xs = []
	ys = []
	for y in 0...8
		gets.split('').each.with_index do |c, x|
			if c == 'K'
				xs << x % 4
				ys << y % 4
			end
		end
	end
	if xs[0] == xs[1] and ys[0] == ys[1]
		puts 'YES'
	else
		puts 'NO'
	end
	if i < t-1
		gets
	end
end

valid_pos = [[0, 4], [4, 0], [4, 4]]

n = gets.to_i
for k in 1..n
  kings = []
  for i in 0..7
    s = gets.chomp.split('')
    for j in 0..7
      kings << [i, j] if s[j] == 'K'
    end
  end
  puts(valid_pos.include?([(kings[1][0] - kings[0][0]).abs, (kings[1][1] - kings[0][1]).abs]) ? 'YES' : 'NO')
  gets if k < n
end

t = gets.to_i
for i in 0...t
	sum = []
	diff = []
	for y in 0...8
		gets.split('').each.with_index do |c, x|
			if c == 'K'
				sum << (x + y) % 4
				diff << (x - y) % 4
			end
		end
	end
	if sum[0] == sum[1] and diff[0] == diff[1]
		puts 'YES'
	else
		puts 'NO'
	end
	if i < t-1
		gets
	end
end

valid_pos = [[2, 2], [0, 4], [4, 0], [4, 4], [5, 2], [2, 6], [6, 6]]

n = gets.to_i
for k in 1..n
  kings = []
  for i in 0..7
    s = gets.chomp.split('')
    for j in 0..7
      kings << [i, j] if s[j] == 'K'
    end
  end
  puts(valid_pos.include?([(kings[1][0] - kings[0][0]).abs, (kings[1][1] - kings[0][1]).abs]) ? 'YES' : 'NO')
  gets if k < n
end

valid_pos = [[2, 2], [0, 4], [4, 0], [4, 4], [4, 2], [2, 6], [6, 6]]

n = gets.to_i
for k in 1..n
  kings = []
  for i in 0..7
    s = gets.chomp.split('')
    for j in 0..7
      kings << [i, j] if s[j] == 'K'
    end
  end
  puts(valid_pos.include?([(kings[1][0] - kings[0][0]).abs, (kings[1][1] - kings[0][1]).abs]) ? 'YES' : 'NO')
  gets if k < n
end

valid_pos = [[2, 2], [0, 4], [4, 0], [4, 4]]

n = gets.to_i
for k in 1..n
  kings = []
  for i in 0..7
    s = gets.chomp.split('')
    for j in 0..7
      kings << [i, j] if s[j] == 'K'
    end
  end
  puts(valid_pos.include?([(kings[1][0] - kings[0][0]).abs, (kings[1][1] - kings[0][1]).abs]) ? 'YES' : 'NO')
  gets if k < n
end


Everybody knows that the $$$m$$$-coder Tournament will happen soon. $$$m$$$ schools participate in the tournament, and only one student from each school participates.There are a total of $$$n$$$ students in those schools. Before the tournament, all students put their names and the names of their schools into the Technogoblet of Fire. After that, Technogoblet selects the strongest student from each school to participate. Arkady is a hacker who wants to have $$$k$$$ Chosen Ones selected by the Technogoblet. Unfortunately, not all of them are the strongest in their schools, but Arkady can make up some new school names and replace some names from Technogoblet with those. You can't use each made-up name more than once. In that case, Technogoblet would select the strongest student in those made-up schools too.You know the power of each student and schools they study in. Calculate the minimal number of schools Arkady has to make up so that $$$k$$$ Chosen Ones would be selected by the Technogoblet.

The first line contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$1 \le n \le 100$$$, $$$1 \le m, k \le n$$$) — the total number of students, the number of schools and the number of the Chosen Ones. The second line contains $$$n$$$ different integers $$$p_1, p_2, \ldots, p_n$$$ ($$$1 \le p_i \le n$$$), where $$$p_i$$$ denotes the power of $$$i$$$-th student. The bigger the power, the stronger the student. The third line contains $$$n$$$ integers $$$s_1, s_2, \ldots, s_n$$$ ($$$1 \le s_i \le m$$$), where $$$s_i$$$ denotes the school the $$$i$$$-th student goes to. At least one student studies in each of the schools.  The fourth line contains $$$k$$$ different integers $$$c_1, c_2, \ldots, c_k$$$ ($$$1 \le c_i \le n$$$)  — the id's of the Chosen Ones.

Output a single integer  — the minimal number of schools to be made up by Arkady so that $$$k$$$ Chosen Ones would be selected by the Technogoblet.

NoteIn the first example there's just a single Chosen One with id $$$3$$$. His power is equal to $$$3$$$, but in the same school $$$1$$$, there's a student with id $$$5$$$ and power $$$6$$$, and that means inaction would not lead to the latter being chosen. If we, however, make up a new school (let its id be $$$4$$$) for the Chosen One, Technogoblet would select students with ids $$$2$$$ (strongest in $$$3$$$), $$$5$$$ (strongest in $$$1$$$), $$$6$$$ (strongest in $$$2$$$) and $$$3$$$ (strongest in $$$4$$$).In the second example, you can change the school of student $$$3$$$ to the made-up $$$5$$$ and the school of student $$$4$$$ to the made-up $$$6$$$. It will cause the Technogoblet to choose students $$$8$$$, $$$7$$$, $$$6$$$, $$$5$$$, $$$3$$$ and $$$4$$$.

a = gets.rstrip.split.map(&:to_i)
n = a[0]
m = a[1]
k = a[2]

powers = gets.rstrip.split.map(&:to_i)
schools = gets.rstrip.split.map(&:to_i)
chosen = gets.rstrip.split.map(&:to_i)
count = 0
chosen.each do |chosen_one|
	school = schools[chosen_one - 1]
	max_power = 0
	schools.each_with_index do |student, i|
		next unless student == school
		max_power = powers[i] if max_power < powers[i]
	end
	count += 1 if powers[chosen_one - 1] < max_power
end

p count

n, m, k = gets.strip.split(" ").map(&:to_i)

powers  = gets.split(" ").map(&:to_i)
schools = gets.split(" ").map(&:to_i)
choosens = gets.split(" ").map(&:to_i)

made_up_cnt = 0
choosens.each do |student|
  schools.each_with_index do |school, index|
    if student-1 != index and schools[student-1] == school and powers[student-1] < powers[index]
      made_up_cnt += 1
      break
    end
  end
end

puts made_up_cnt

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

nmk = gets.chomp.split(" ").map(&:to_i)
n = nmk[0]
m = nmk[1]
k = nmk[2]

power = gets.chomp.split(" ").map(&:to_i)
schools = gets.chomp.split(" ").map(&:to_i)
chosen = gets.chomp.split(" ").map(&:to_i)

schoolsarr = []
m.times {schoolsarr.push []}

(0..n-1).each do |i|
	schoolsarr[schools[i]-1].push power[i]
end

(0..m-1).each do |i|
	schoolsarr[i].sort!
end

ans = 0

#p schoolsarr

chosen.each do |z|
	ind = z-1
#	p ind
#	p schools[ind]
	if (power[ind]!=schoolsarr[schools[ind]-1][-1])
		ans+=1
	end
end

puts ans

n, m, k = gets.strip.split(" ").map(&:to_i)

powers  = gets.split(" ").map(&:to_i)
schools = gets.split(" ").map(&:to_i)
choosens = gets.split(" ").map(&:to_i)

made_up_cnt = 0
choosens.each do |student|
  schools.each_with_index do |school, index|
    if schools[student-1] == school and powers[student-1] < powers[index]
      made_up_cnt += 1
    end
  end
end

puts made_up_cnt

n, m, k = gets.strip.split(" ").map(&:to_i)

powers  = gets.split(" ").map(&:to_i)
schools = gets.split(" ").map(&:to_i)
choosens = gets.split(" ").map(&:to_i)

made_up_cnt = 0
choosens.each do |student|
  schools.each_with_index do |school, index|
    if student-1 != index and schools[student-1] == school and powers[student-1] < powers[index]
      made_up_cnt += 1
    end
  end
end

puts made_up_cnt


The main road in Bytecity is a straight line from south to north. Conveniently, there are coordinates measured in meters from the southernmost building in north direction.At some points on the road there are n friends, and i-th of them is standing at the point xi meters and can move with any speed no greater than vi meters per second in any of the two directions along the road: south or north.You are to compute the minimum time needed to gather all the n friends at some point on the road. Note that the point they meet at doesn't need to have integer coordinate.

The first line contains single integer n (2 ≤ n ≤ 60 000) — the number of friends. The second line contains n integers x1, x2, ..., xn (1 ≤ xi ≤ 109) — the current coordinates of the friends, in meters. The third line contains n integers v1, v2, ..., vn (1 ≤ vi ≤ 109) — the maximum speeds of the friends, in meters per second.

Print the minimum time (in seconds) needed for all the n friends to meet at some point on the road.  Your answer will be considered correct, if its absolute or relative error isn't greater than 10 - 6. Formally, let your answer be a, while jury's answer be b. Your answer will be considered correct if  holds.

NoteIn the first sample, all friends can gather at the point 5 within 2 seconds. In order to achieve this, the first friend should go south all the time at his maximum speed, while the second and the third friends should go north at their maximum speeds.

#!/usr/bin/env ruby

class MeetingPlace
  attr_accessor :n, :x, :v, :zip, :result

  def get_data
    # fl=File.new "test0.txt"
    # @n,@x,@v = fl.readlines.map {|x| x.split.map(&:to_i)}
    @n, @x, @v = $stdin.readlines.map { |x| x.split.map(&:to_i) }
    @n = @n[0]
  end

  def output
    puts @result
  end

  def init
    @zip = @x.zip @v
    @x, @v = nil, nil
    @zip = @zip.sort { |a, b| a[0]<=>b[0] }
    @zipUp = @zip.each
    @zipDown = @zip.reverse_each
    @upper = @zipDown.next
    @lower =@zipUp.next
    @upperPrev = @upper
    @lowerPrev = @lower
    @direction = nil
    @result = (@upper[0] - @lower[0]).to_f / (@upper[1] + @lower[1])
    @lowerPtr = 0
    @upperPtr = @zip.length - 1
  end

  def getNext
    return false if @lowerPtr == @upperPtr
    if @upper[1] > @lower[1]
      @upper = @zipDown.next
      @direction = :down
      @upperPtr-=1
    else
      @lower = @zipUp.next
      @direction = :up
      @lowerPtr+=1
    end
    true
  end

  def get_result
    init
    while getNext
      if @direction == :down
        tmp = (@upper[0] - @lowerPrev[0]).to_f / (@upper[1] + @lowerPrev[1])
      else
        tmp = (@upperPrev[0] - @lower[0]).to_f / (@upperPrev[1] + @lower[1])
      end
      if tmp > @result
        @result = tmp
        if @upper[1] != @upperPrev[1]
          @upperPrev = @upper
        else
          @lowerPrev = @lower
        end
      end
    end
    @result = @result.round(6)
  end
end

if __FILE__ == $0
  mp = MeetingPlace.new
  mp.get_data
  mp.get_result
  mp.output
end

def read_ints
  gets.split.map(&:to_i)
end

n = gets.to_i
a = read_ints.zip(read_ints)

l = 0.0
r = 1e9
100.times do
  c = (l + r) / 2
  mx = a.map{|x, v| x - v * c}.max
  mi = a.map{|x, v| x + v * c}.min
  if mx > mi
    l = c
  else
    r = c
  end
end
p (l + r) / 2

gets
xv = gets.split.map(&:to_f).zip(gets.split.map(&:to_f)).sort
aa, res = (bb = []), [0.0]
begin
  u = 2e9
  xv.each { |x, v|
    if u > v
      u = v
      bb << [x, v]
    end
  }
  break if !aa.equal?(bb)
  bb = []
  xv.reverse!
end while true
aa.each { |x, v|
  bb.each { |y, u|
    break if y <= x
    res << (y - x) / (u + v)
  }
}
p res.max

#!/usr/bin/env ruby

class MeetingPlace
  attr_accessor :n, :x, :v, :zip, :result

  def get_data
    # fl=File.new "test0.txt"
    # @n,@x,@v = fl.readlines.map {|x| x.split.map(&:to_i)}
    @n, @x, @v = $stdin.readlines.map { |x| x.split.map(&:to_i) }
    @n = @n[0]
  end

  def output
    puts @result
  end

  def init
    @zip = @x.zip @v
    @x, @v = nil, nil
    @zip = @zip.sort { |a, b| a[0]<=>b[0] }
    @zipUp = @zip.each
    @zipDown = @zip.reverse_each
    @upper = @zipDown.next
    @lower =@zipUp.next
    @upperPrev = @upper
    @lowerPrev = @lower
    @result = (@upper[0] - @lower[0]).to_f / (@upper[1] + @lower[1])
  end

  def getNext
    return false if @upper[0] == @lower[0]
    if @upper[1] > @lower[1]
      @upper = @zipDown.next
    else
      @lower = @zipUp.next
    end
    true
  end

  def get_result
    init
    while getNext
      tmp = (@upper[0] - @lower[0]).to_f / (@upper[1] + @lower[1])
      @result = tmp if tmp > @result
    end
    @result = @result.round(6)
  end
end

if __FILE__ == $0
  mp = MeetingPlace.new
  mp.get_data
  mp.get_result
  mp.output
end