Sereja and Dima play a game. The rules of the game are very simple. The players have n cards in a row. Each card contains a number, all numbers on the cards are distinct. The players take turns, Sereja moves first. During his turn a player can take one card: either the leftmost card in a row, or the rightmost one. The game ends when there is no more cards. The player who has the maximum sum of numbers on his cards by the end of the game, wins.Sereja and Dima are being greedy. Each of them chooses the card with the larger number during his move.Inna is a friend of Sereja and Dima. She knows which strategy the guys are using, so she wants to determine the final score, given the initial state of the game. Help her.

The first line contains integer n (1 ≤ n ≤ 1000) — the number of cards on the table. The second line contains space-separated numbers on the cards from left to right. The numbers on the cards are distinct integers from 1 to 1000.

On a single line, print two integers. The first number is the number of Sereja's points at the end of the game, the second number is the number of Dima's points at the end of the game.

NoteIn the first sample Sereja will take cards with numbers 10 and 2, so Sereja's sum is 12. Dima will take cards with numbers 4 and 1, so Dima's sum is 5.

n = gets.to_i
card = gets.split(' ').map(&:to_i)
change = {Sereja: :Dima, Dima: :Sereja}
player = :Sereja
point = {Sereja: 0, Dima: 0}
until card.length == 0
  if card.first > card.last
    point[player] += card.delete_at(0)
  else
    point[player] += card.delete_at(-1)
  end
  player = change[player]
end
puts "#{point[:Sereja]} #{point[:Dima]}"

#!/usr/bin/ruby
gets
a=gets.split.map(&:to_i)
r=[0,0]
f=0
while !a.empty?
	if a.first>a.last
		r[f]+=a.shift
	else
		r[f]+=a.pop
	end
	f^=1
end
puts r*' '

n = gets.chomp.to_i
arr = gets.chomp.split(' ').map{|x| x.to_i}
l = 0
r = n-1
b = [0, 0]
p = 0
while l <= r
	if arr[l] >= arr[r]
		b[p] += arr[l]
		l += 1
	elsif
		b[p] += arr[r]
		r -= 1
	end
	p = 1-p
end
print b[0], " ", b[1]

n = gets.to_i
a = gets.split.map &:to_i
l = 0
r = n - 1
s = [0, 0]
turn = 0
while l <= r do
    if a[l] >= a[r] then
        s[turn] += a[l]
        l += 1
    else
        s[turn] += a[r]
        r -= 1
    end
    turn = 1 - turn
end
puts s[0].to_s + ' ' + s[1].to_s

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

i, j = 0, n - 1;
ans = [0, 0];
count = 0;

n.times {
  if (arr[i] > arr[j])
    ans[count] += arr[i];
    i += 1;
  else
    ans[count] += arr[j];
    j -= 1;
  end
  count = 1 - count;
}
# print ans , "\n";
puts ans;

n = gets.to_i
cards = gets.split.map(&:to_i)
sereja = 0
dima = 0
turn = 1
until cards.size == 0
	if turn == 1
		if cards[0] > cards[-1]
			sereja += cards[0]
			cards.shift
		else
			sereja += cards[-1]
			cards.pop
		end
	else
		if cards[0] > cards[-1]
			dima += cards[0]
			cards.shift
		else
			dima += cards[-1]
			cards.pop
		end
	end
	turn *= -1
end

puts "#{sereja} #{dima}"

#!/usr/bin/ruby

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

seq = []
while a.size > 0
  if a.first > a.last
    seq << a.shift
  else
    seq << a.pop
  end
end

if seq.size % 2 == 1
  seq << 0
end

s1 = 0
s2 = 0
while seq.size > 0
  s1 += seq.shift
  s2 += seq.shift
end

puts "#{s1} #{s2}"

n = gets.chomp.to_i
a = gets.chomp.split.map(&:to_i)
ans = Array.new(2, 0)
l, r, turn = 0, n - 1, 0
while l <= r do
  if a[l] > a[r]
    ans[turn] += a[l]
    l += 1
  else
    ans[turn] += a[r]
    r -= 1
  end
  turn = 1 - turn
end
puts [ans[0], ans[1]].join(' ')

n=gets.to_i
a=gets.split.map(&:to_i)
s=[0]*2
c=0
while c<n
 s[c%2]+=a[0]>a[-1] ? a.shift : a.pop
 c+=1
end
puts s*' '

def run
  n = $stdin.gets.to_i
  a = $stdin.gets.split.map(&:to_i)
  s = [0, 0]
  c = 0
  while a.length > 0
    s[c % 2] += a[0] > a[-1] ? a.shift : a.pop
    c += 1
  end
  puts s.join(" ")
end

run if $0 == __FILE__

n = gets.to_i
arr = gets.split(" ").map(&:to_i)
ans = [0,0]
toggle_bit = 0
until arr.empty?
    if (arr.first > arr.last)
        ans[toggle_bit] += arr.shift
    else
        ans[toggle_bit] += arr.pop
    end
    toggle_bit ^=1
end

puts "#{ans[0]} #{ans[1]}"

# cook your code here
n = gets.to_i
arr = gets.split(" ").map(&:to_i)
sereja = 0
dima = 0
count =0
val =0
len = arr.size-1
last_ind = len
firt_ind = 0
while firt_ind <= last_ind
    if arr[firt_ind] < arr[last_ind]
        val  = arr[last_ind]
        last_ind -=1
    else
        val = arr[firt_ind]
        firt_ind +=1
    end

    sereja += val if count ==0
    dima += val if count == 1
    if count ==0
        count = 1
    else
        count =0
    end

end

puts "#{sereja} #{dima}"

class A
  def initialize
    n = gets.chomp.to_i
    cards = gets.chomp.split(' ').map(&:to_i)
    sere = 0
    dima = 0
    turn = 0
    val = 0

    until cards.size.zero? do
      val = ( cards.first < cards.last )? cards.pop : cards.shift
      if turn.odd?
        dima += val
      else
        sere += val
      end
      turn += 1
    end
    puts "#{sere} #{dima}"
  end
end

A.new

a=gets.chomp.to_i
b=gets.chomp.split(" ")
if a%2==0
s=0
r=0
(a/2).times do
if b[0].to_i > b[ b.length-1].to_i
s+=b[0].to_i
b.delete_at(0)
else
s+=b[b.length-1].to_i
b.delete_at(b.length-1)
end
if b[0].to_i>b[b.length-1].to_i
r+=b[0].to_i
b.delete_at(0)
else
r+=b[b.length-1].to_i
b.delete_at(b.length-1)
end
end
else
s=0
r=0
(a/2).times do
if b[0].to_i > b[ b.length-1].to_i
s+=b[0].to_i
b.delete_at(0)
else
s+=b[b.length-1].to_i
b.delete_at(b.length-1)
end
if b[0].to_i>b[b.length-1].to_i
r+=b[0].to_i
b.delete_at(0)
else
r+=b[b.length-1].to_i
b.delete_at(b.length-1)
end
end
s+=b[0].to_i
end

puts "#{s} #{r}"

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

s = 0
d = 0
t = 0
while !cs.empty? do
  if cs[0] > cs[-1]
    c = cs.shift
  else
    c = cs.pop
  end

  if t % 2 == 0
    s += c
  else
    d += c
  end
  t += 1
end

puts "#{s} #{d}"

n=gets.to_i
x=gets.split.map{|e| e.to_i}

i=0
a=0
b=0
while !x.empty?
	t=0
	if x[0]<x.last then
		t=x.last
		x.pop
	else
		t=x[0]
		x.shift
	end
	if i==0 then
		a+=t
	else
		b+=t
	end
	i=1-i
end
puts [a,b]*" "

numberOfCards = gets.chomp.to_i
cards = gets.chomp.split(' ').map { |x| x.to_i }
player = 0
scores = [0, 0]

while not cards.count.zero?
  if cards.first > cards.last
    scores[player] += cards.shift
  else
    scores[player] += cards.pop
  end
  player = (player + 1) % 2
end

puts "#{scores[0]} #{scores[1]}"

# coding : utf-8

# if __FILE__ == $0
# end

n = gets.to_i
cards = gets.split.map(&:to_i)
sereja, dima = 0, 0 # sereja goes first

while !cards.empty?
    # serja
    if cards.first > cards.last
        sereja += cards.shift
    else
        sereja += cards.pop
    end

    unless cards.empty?
        # dima
        if cards.first > cards.last
            dima += cards.shift
        else
            dima += cards.pop
        end
    end
end

puts "#{sereja} #{dima}"

n = $stdin.gets.to_i
cards = $stdin.gets.chomp.split(' ').map{|e| e.to_i}

pls = [0, 0]
plnum = 0
until cards.empty?
    d = [cards.first, cards.last].max
    pls[plnum] += d
    cards.delete d
    plnum = plnum == 0 ? 1 : 0
end

puts pls.join ' '

n = gets.to_i
a = gets.split.map(&:to_i)
sol = [0, 0]
n.times do |i|
   if a.first > a.last
     sol[i % 2] += a.first
     a.shift
   else
     sol[i % 2] += a.last
     a.pop
   end
end
puts sol.join(" ")

n = gets.to_i
a = gets.split.map(&:to_i)
npoints, i = [0, 0], 0
while a.size > 0
  if a[0] > a[-1]
    npoints[i%2] += a[0]
    a = a[1..-1]
  else
    npoints[i%2] += a[-1]
    a = a[0..-2]
  end
  i += 1
end
puts npoints.join(' ')

n=gets.to_i
a=gets.split.map(&:to_i)
c=0
b=[0,0]
while a.size>0
  if a[0]>a[-1]
    b[c%2]+=a[0]
    a.shift
  else
    b[c%2]+=a[-1]
    a.pop
  end
  c+=1
end
puts b*' '

def solution(n, cards)
  l, sereja, dima, count = 0, 0, 0, 0
  r = n-1
  while (l <= r ) do
    if cards[l] > cards [r]
      sereja += cards[l]
      l += 1
      count += 1
    else
      sereja += cards[r]
      r -= 1
      count += 1
    end
    if count <= n/2
      if cards[l] > cards[r]
        dima += cards[l]
        l += 1
      else
        dima += cards[r]
        r -= 1
      end
    end
  end
  puts "#{sereja} #{dima}"
end

solution(gets.chomp.to_i, gets.split.map(&:to_i))

def solution(n, cards)
  l, sereja, dima, count = 0, 0, 0, 0
  r = n-1
  while (l <= r ) do
    if cards[l] > cards [r]
      sereja += cards[l]
      l += 1
      count += 1
    else
      sereja += cards[r]
      r -= 1
      count += 1
    end
    if r >= 0 && count <= n/2
      if cards[l] > cards[r]
        dima += cards[l]
        l += 1
      else
        dima += cards[r]
        r -= 1
      end
    end
  end
  puts "#{sereja} #{dima}"
end

solution(gets.chomp.to_i, gets.split.map(&:to_i))

# http://codeforces.com/problemset/problem/381/A

n = gets.chomp.to_i

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

l, r = 0, n - 1

sereja_move = true
result = 0
while l < n && r >= 0 && l <= r
  max = [list[l], list[r]].max

  if sereja_move
    result += max
  end

  if list[l] < list[r]
    r -= 1
  else
    l += 1
  end
  sereja_move = !sereja_move
end

print result, " ", list.inject(:+) - result

# http://codeforces.com/problemset/problem/381/A

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

l, r = 0, n - 1
sereja_move = true
result = 0

while l < n && r >= 0 && l <= r
  if list[l] < list[r]
    max = list[r]
    r -= 1
  else
    max = list[l]
    l += 1
  end

  result += max if sereja_move
  sereja_move = !sereja_move
end

print result, " ", list.inject(:+) - result

# http://codeforces.com/problemset/problem/381/A

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

l, r = 0, n - 1
sereja_move = true
result1 = 0
result2 = 0

while l < n && r >= 0 && l <= r
  if list[l] < list[r]
    max = list[r]
    r -= 1
  else
    max = list[l]
    l += 1
  end

  sereja_move ? result1 += max : result2 += max
  sereja_move = !sereja_move
end

print result1, " ", result2

gets
a = gets.split(' ').map(&:to_i)
s = [0, 0]

0.upto(a.size-1) do |i|
  s[i % 2] += [a.first, a.last].max

  a.__send__(a.first > a.last ? :shift : :pop)
end

puts s.join(' ')

gets
cards = gets.split.map(&:to_i)
result = [0, 0]
i = 0
until cards.empty?
  if cards.first > cards.last
    result[i] += cards.shift
  else
    result[i] += cards.pop
  end
  i += 1
  i %= 2
end
puts result.join ' '

n = gets().to_i
arr = gets.split.map(&:to_i)
l = 0
r = n-1
one = 0
two = 0
turn = true
while l <= r do
    if arr[l] >= arr[r]
        if turn
            one += arr[l]
        else
            two += arr[l]
        end
        l+=1
    else
        if turn
            one += arr[r]
        else
            two += arr[r]
        end
        r-=1
    end
    turn = !turn
end
print one," ",two,"\n"

cardNum = gets.chomp.to_i
cards = gets.chomp.split(' ').map {|i| i.to_i}

players = Array.new(2) {|i| i = 0}
nowTurn = 0

until cards.length == 0
	if cards[0] > cards[cards.length - 1]
		players[nowTurn] += cards[0]
		cards.delete_at(0)
	else
		players[nowTurn] += cards[cards.length - 1]
		cards.delete_at(cards.length - 1)
	end

	nowTurn = (nowTurn + 1) % players.length
end

puts "#{players[0]} #{players[1]}"

n = gets.to_i
arr = gets.split(" ").map(&:to_i)
arr.sort!
sereja = 0
dima = 0
count =0
arr.reverse.each do |a|
    sereja += a if count == 0
    dima +=a    if count ==1
    if count == 0
        count = 1
    else
        count =0
    end

end
puts "#{sereja} #{dima}"

# cook your code here
n = gets.to_i
arr = gets.split(" ").map(&:to_i)
arr.sort!
sereja = 0
dima = 0
arr.each_with_index do |a,ind|
    if ind.even?
        dima += a
    else
        sereja +=a
    end

end
puts "#{dima} #{sereja}"

def solution(n, cards)
  l, sereja, dima = 0, 0, 0
  r = n-1
  while (l <= r ) do

    if cards[l] > cards [r]
      sereja += cards[l]
      l += 1
    else
      sereja += cards[r]
      r -= 1
    end
    if cards[l] > cards[r]
      dima += cards[l] if l < n
      l += 1
    else
      dima += cards[r] if r >0
      r -= 1
    end
  end
  puts "#{sereja} #{dima}"
end

solution(gets.chomp.to_i, gets.split.map(&:to_i))

gets
cards = gets.split.map(&:to_i).sort.each_slice(2)
result = cards.inject { |a, b|
  a[0] += b[0]
  a[1] += b[1].to_i
  a
}
# p result
puts result.sort.reverse.join ' '

gets
cards = gets.split.map(&:to_i)
result = [0, 0]
i = 0
until cards.empty?
  if cards.first > cards.last
    result[i] += cards.shift
  else
    result[i] += cards.pop
  end
  i += 1
  i %= 2
end
puts result.sort.reverse.join ' '


You are given the following points with integer coordinates on the plane: M0, A0, A1, ..., An - 1, where n is odd number. Now we define the following infinite sequence of points Mi: Mi is symmetric to Mi - 1 according  (for every natural number i). Here point B is symmetric to A according M, if M is the center of the line segment AB. Given index j find the point Mj.

On the first line you will be given an integer n (1 ≤ n ≤ 105), which will be odd, and j (1 ≤ j ≤ 1018), where j is the index of the desired point. The next line contains two space separated integers, the coordinates of M0. After that n lines follow, where the i-th line contain the space separated integer coordinates of the point Ai - 1. The absolute values of all input coordinates will not be greater then 1000.

On a single line output the coordinates of Mj, space separated.

n, m = gets.split.map { |v| v.to_i }
m = m % (2 * n)

x, y = gets.split.map { |v| v.to_i }
a = Array.new(n) { gets.split.map { |v| v.to_i } }

(0 ... m).each do |index|
  x = 2 * a[index % n][0] - x
  y = 2 * a[index % n][1] - y
end

puts "#{x} #{y}"

n, m = gets.split.map { |v| v.to_i }
m = m % (2 * n - 1)

x, y = gets.split.map { |v| v.to_i }
a = Array.new(n) { gets.split.map { |v| v.to_i } }

(0 ... m).each do |index|
  x = 2 * a[index % n][0] - x
  y = 2 * a[index % n][1] - y
end

puts "#{x} #{y}"

n, m = gets.split.map { |v| v.to_i }
m = m % 2 * n

x, y = gets.split.map { |v| v.to_i }
a = Array.new(n) { gets.split.map { |v| v.to_i } }

(0 ... m).each do |index|
  x = 2 * a[index % n][0] - x
  y = 2 * a[index % n][1] - y
end

puts "#{x} #{y}"


This problem is different from the easy version. In this version Ujan makes at most $$$2n$$$ swaps. In addition, $$$k \le 1000, n \le 50$$$ and it is necessary to print swaps themselves. You can hack this problem if you solve it. But you can hack the previous problem only if you solve both problems.After struggling and failing many times, Ujan decided to try to clean up his house again. He decided to get his strings in order first.Ujan has two distinct strings $$$s$$$ and $$$t$$$ of length $$$n$$$ consisting of only of lowercase English characters. He wants to make them equal. Since Ujan is lazy, he will perform the following operation at most $$$2n$$$ times: he takes two positions $$$i$$$ and $$$j$$$ ($$$1 \le i,j \le n$$$, the values $$$i$$$ and $$$j$$$ can be equal or different), and swaps the characters $$$s_i$$$ and $$$t_j$$$.Ujan's goal is to make the strings $$$s$$$ and $$$t$$$ equal. He does not need to minimize the number of performed operations: any sequence of operations of length $$$2n$$$ or shorter is suitable.

The first line contains a single integer $$$k$$$ ($$$1 \leq k \leq 1000$$$), the number of test cases. For each of the test cases, the first line contains a single integer $$$n$$$ ($$$2 \leq n \leq 50$$$), the length of the strings $$$s$$$ and $$$t$$$.  Each of the next two lines contains the strings $$$s$$$ and $$$t$$$, each having length exactly $$$n$$$. The strings consist only of lowercase English letters. It is guaranteed that strings are different.

For each test case, output "Yes" if Ujan can make the two strings equal with at most $$$2n$$$ operations and "No" otherwise. You can print each letter in any case (upper or lower). In the case of "Yes" print $$$m$$$ ($$$1 \le m \le 2n$$$) on the next line, where $$$m$$$ is the number of swap operations to make the strings equal. Then print $$$m$$$ lines, each line should contain two integers $$$i, j$$$ ($$$1 \le i, j \le n$$$) meaning that Ujan swaps $$$s_i$$$ and $$$t_j$$$ during the corresponding operation. You do not need to minimize the number of operations. Any sequence of length not more than $$$2n$$$ is suitable.

4
5
souse
houhe
3
cat
dog
2
aa
az
3
abc
bca

#599 (Div. 2), problem: (B2) Character Swap (Hard Version), Wrong answer on test 2, #
def inpf() a=gets.chomp.split(" ").map(&:to_f)end

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

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

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

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

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

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

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

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

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

q = inp[0]
nt = []
st = []
tt = []
q.times do
  nt << inp[0]
  st << gets.chomp
  tt << gets.chomp
end
q.times do |i|
  n = nt[i]
  s = st[i]
  t = tt[i]
  m = na(27)
  m[-1] = 999999
  ao = "a".ord
  n.times do |i|
    m[s[i].ord - ao] += 1
    m[t[i].ord - ao] += 1
  end
  f = true
  26.times do |i|
    if m[i].odd?
      f = false
    end
  end
  at = ""

  mm = copy(m)
  mm.map{|d|d/2}
  if (f)
    ans = []
    n.times do |i|
      at += s[i]
      at += t[i]
    end
    pt = at
    pt = pt.split("").sort!.join("")
    i = 0
    n.times do |i|
      if s[i] != t[i]
        ind = 0
        (i...n).reverse_each do |j|
          if(s[j] == s[i])
            s[j],t[i] = t[i],s[j]
            ans.push([j+1,i+1])
            break
          end
        end
        next if s[i] == t[i]
        (i...n).reverse_each do |j|
          if(t[i] == t[j])
            s[i],t[j] = t[j],s[i]
            ans.push([i+1,j+1])
            break
          end
        end
      end
    end
    puts "Yes"
    puts ans.size
    ans.size.times do |i|
      puts ans[i].join(" ")
    end
  else
    puts "No"
    next
  end
end

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

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

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

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

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

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

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

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

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

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

q = inp[0]
nt = []
st = []
tt = []
q.times do
  nt << inp[0]
  st << gets.chomp
  tt << gets.chomp
end
q.times do |i|
  n = nt[i]
  s = st[i]
  t = tt[i]
  m = na(27)
  m[-1] = 999999
  ao = "a".ord
  n.times do |i|
    m[s[i].ord - ao] += 1
    m[t[i].ord - ao] += 1
  end
  f = true
  26.times do |i|
    if m[i].odd?
      f = false
    end
  end
  at = ""

  mm = copy(m)
  mm.map{|d|d/2}
  if (f)
    ans = []
    n.times do |i|
      at += s[i]
      at += t[i]
    end
    pt = at
    pt = pt.split("").sort!.join("")
    i = 0
    n.times do |i|
      if s[i] != t[i]
        ind = 0
        (i...n).reverse_each do |j|
          if(s[j] == s[i])
            s[j],t[i] = t[i],s[j]
            ans.push([i+1,j+1])
            break
          end
        end
        next if s[i] == t[i]
        (i...n).reverse_each do |j|
          if(t[j] == t[j])
            s[i],t[j] = t[j],s[i]
            ans.push([j+1,i+1])
            break
          end
        end
      end
    end
    puts "Yes"
    puts ans.size
    ans.size.times do |i|
      puts ans[i].join(" ")
    end
  else
    puts "No"
    next
  end
end

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

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

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

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

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

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

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

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

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

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

q = inp[0]
nt = []
st = []
tt = []
q.times do
  nt << inp[0]
  st << gets.chomp
  tt << gets.chomp
end
q.times do |i|
  n = nt[i]
  s = st[i]
  t = tt[i]
  m = na(27)
  m[-1] = 999999
  ao = "a".ord
  n.times do |i|
    m[s[i].ord - ao] += 1
    m[t[i].ord - ao] += 1
  end
  f = true
  26.times do |i|
    if m[i].odd?
      f = false
    end
  end
  at = ""

  mm = copy(m)
  mm.map{|d|d/2}
  if (f)
    ans = []
    n.times do |i|
      at += s[i]
      at += t[i]
    end
    pt = at
    pt = pt.split("").sort!.join("")
    i = 0
    n.times do |i|
      if s[i] != t[i]
        ind = 0
        (i...n).reverse_each do |j|
          if(s[j] == s[i])
            s[j],t[i] = t[i],s[j]
            ans.push([j+1,i+1])
            break
          end
        end
        next if (s[i] == t[i])
        (i...n).reverse_each do |j|
          if(s[j] == s[i])
            s[j],t[i] = t[i],s[j]
            ans.push([j+1,i+1])
            break
          end
        end
      end
    end

    puts "Yes"
    puts ans.size
    ans.size.times do |i|
      puts ans[i].join(" ")
    end
  else
    puts "No"
    next
  end
end

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

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

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

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

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

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

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

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

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

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

q = inp[0]
nt = []
st = []
tt = []
q.times do
  nt << inp[0]
  st << gets.chomp
  tt << gets.chomp
end
q.times do |i|
  n = nt[i]
  s = st[i]
  t = tt[i]
  m = na(27)
  m[-1] = 999999
  ao = "a".ord
  n.times do |i|
    m[s[i].ord - ao] += 1
    m[t[i].ord - ao] += 1
  end
  f = true
  26.times do |i|
    if m[i].odd?
      f = false
    end
  end
  at = ""

  mm = copy(m)
  mm.map{|d|d/2}
  if (f)
    ans = []
    n.times do |i|
      at += s[i]
      at += t[i]
    end
    pt = at
    pt = pt.split("").sort!.join("")
    (n*2).times do |ii|
      i = ii/2
      if s[i] != pt[ii]
        ind = 0
        ((i+ii%2)...(n)).each do |j|
          if(t[j] == pt[ii])
            ind = j
          end
        end
        ans.push([i+1,ind+1])
        s[i], t[ind] = t[ind], s[i]
      end
      if t[i] != pt[ii]
        ind = 0
        ((i+ii%2)...(n)).each do |j|
          if(s[j] == pt[ii])
            ind = j
          end
        end
        ans.push([ind+1,i+1])
        t[i], s[ind] = s[ind], t[i]
      end
    end

    puts ans.size
    ans.size.times do |i|
      puts ans[i].join(" ")
    end
  else
    puts "No"
    next
  end
end

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

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

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

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

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

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

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

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

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

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

q = inp[0]
nt = []
st = []
tt = []
q.times do
  nt << inp[0]
  st << gets.chomp
  tt << gets.chomp
end
q.times do |i|
  n = nt[i]
  s = st[i]
  t = tt[i]
  m = na(27)
  m[-1] = 999999
  ao = "a".ord
  n.times do |i|
    m[s[i].ord - ao] += 1
    m[t[i].ord - ao] += 1
  end
  f = true
  26.times do |i|
    if m[i].odd?
      f = false
    end
  end
  at = ""

  mm = copy(m)
  mm.map{|d|d/2}
  if (f)
    ans = []
    n.times do |i|
      at += s[i]
      at += t[i]
    end
    pt = at
    pt = pt.split("").sort!.join("")
    i = 0
    n.times do |i|
      if s[i] != t[i]
        ind = 0
        (i...n).reverse_each do |j|
          if(s[j] == s[i])
            s[j],t[i] = t[i],s[j]
            ans.push([j+1,i+1])
            break
          end
        end
        (i...n).reverse_each do |j|
          if(s[j] == s[i])
            s[j],t[i] = t[i],s[j]
            ans.push([j+1,i+1])
            break
          end
        end
      end
    end

    puts "Yes"
    puts ans.size
    ans.size.times do |i|
      puts ans[i].join(" ")
    end
  else
    puts "No"
    next
  end
end

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

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

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

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

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

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

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

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

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

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

q = inp[0]
nt = []
st = []
tt = []
q.times do
  nt << inp[0]
  st << gets.chomp
  tt << gets.chomp
end
q.times do |i|
  n = nt[i]
  s = st[i]
  t = tt[i]
  m = na(27)
  m[-1] = 999999
  ao = "a".ord
  n.times do |i|
    m[s[i].ord - ao] += 1
    m[t[i].ord - ao] += 1
  end
  f = true
  26.times do |i|
    if m[i].odd?
      f = false
    end
  end
  at = ""

  mm = copy(m)
  mm.map{|d|d/2}
  if (f)
    ans = []
    n.times do |i|
      at += s[i]
      at += t[i]
    end
    pt = at
    pt = pt.split("").sort!.join("")
    i = 0
    while i < n
      ii = i*2
      if s[i] != pt[ii]
        ind = -1
        ((i)...(n)).reverse_each do |j|
          if(t[j] == pt[ii])
            ind = j
            break
          end
        end
        ans.push([i+1,ind+1])
        s[i], t[ind] = t[ind], s[i] unless ind == -1
        next unless ind == -1
      end
      if t[i] != pt[ii]
        ind = -1
        ((i)...(n)).reverse_each do |j|
          if(s[j] == pt[ii])
            ind = j
            break
          end
        end
        ans.push([ind+1,i+1])
        t[i], s[ind] = s[ind], t[i] unless ind == -1
        next unless ind == -1
      end
      i += 1
    end
    puts "Yes"
    puts ans.size
    ans.size.times do |i|
      puts ans[i].join(" ")
    end
  else
    puts "No"
    next
  end
end

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

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

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

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

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

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

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

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

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

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

q = inp[0]
nt = []
st = []
tt = []
q.times do
  nt << inp[0]
  st << gets.chomp
  tt << gets.chomp
end
q.times do |i|
  n = nt[i]
  s = st[i]
  t = tt[i]
  m = na(27)
  m[-1] = 999999
  ao = "a".ord
  n.times do |i|
    m[s[i].ord - ao] += 1
    m[t[i].ord - ao] += 1
  end
  f = true
  26.times do |i|
    if m[i].odd?
      f = false
    end
  end
  at = ""

  mm = copy(m)
  mm.map{|d|d/2}
  if (f)
    ans = []
    n.times do |i|
      at += s[i]
      at += t[i]
    end
    pt = at
    pt = pt.split("").sort!.join("")
    (n).times do |i|
      if t[i] != pt[i*2]
        ind = 0
        (i...(n)).each do |j|
          if(s[j] == pt[i*2])
            ind = j
            break
          end
        end
        ans.push([ind+1,i+1])
        t[i], s[ind] = s[ind], t[i]
      end
      if s[i] != pt[i*2]
        ind = 0
        ((i+1)...(n)).each do |j|
          if(t[j] == pt[i*2])
            ind = j
            break
          end
        end
        ans.push([i+1,ind+1])
        s[i], t[ind] = t[ind], s[i]
      end
    end
    puts ans.size
    ans.size.times do |i|
      puts ans[i].join(" ")
    end
  else
    puts "No"
    next
  end
end

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

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

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

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

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

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

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

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

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

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

q = inp[0]
nt = []
st = []
tt = []
q.times do
  nt << inp[0]
  st << gets.chomp
  tt << gets.chomp
end
q.times do |i|
  n = nt[i]
  s = st[i]
  t = tt[i]
  m = na(27)
  m[-1] = 999999
  ao = "a".ord
  n.times do |i|
    m[s[i].ord - ao] += 1
    m[t[i].ord - ao] += 1
  end
  f = true
  26.times do |i|
    if m[i].odd?
      f = false
    end
  end
  at = ""

  mm = copy(m)
  mm.map{|d|d/2}
  if (f)
    ans = []
    n.times do |i|
      at += s[i]
      at += t[i]
    end
    pt = at
    pt = pt.split("").sort!.join("")
    i = 0
    n.times do |i|
      if s[i] != t[i]
        ind = 0
        (i...n).reverse_each do |j|
          if(s[j] == s[i])
            s[j],t[i] = t[i],s[j]
            ans.push([j+1,i+1])
            break
          end
        end
        next if s[i] == t[i]
        (i...n).reverse_each do |j|
          if(t[j] == t[j])
            s[i],t[j] = t[j],s[i]
            ans.push([i+1,j+1])
            break
          end
        end
      end
    end
    puts "Yes"
    puts ans.size
    ans.size.times do |i|
      puts ans[i].join(" ")
    end
  else
    puts "No"
    next
  end
end

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

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

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

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

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

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

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

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

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

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

q = inp[0]
nt = []
st = []
tt = []
q.times do
  nt << inp[0]
  st << gets.chomp
  tt << gets.chomp
end
q.times do |i|
  n = nt[i]
  s = st[i]
  t = tt[i]
  m = na(27)
  m[-1] = 999999
  ao = "a".ord
  n.times do |i|
    m[s[i].ord - ao] += 1
    m[t[i].ord - ao] += 1
  end
  f = true
  26.times do |i|
    if m[i].odd?
      f = false
    end
  end
  at = ""

  mm = copy(m)
  mm.map{|d|d/2}
  if (f)
    ans = []
    n.times do |i|
      at += s[i]
      at += t[i]
    end
    pt = at
    pt = pt.split("").sort!.join("")
    i = 0
    while i < n
      ii = i*2
      if s[i] != pt[ii]
        ind = -1
        ((i)...(n)).reverse_each do |j|
          if(t[j] == pt[ii])
            ind = j
            break
          end
        end
        ans.push([i+1,ind+1])
        s[i], t[ind] = t[ind], s[i]
        next unless ind == -1
      end
      if t[i] != pt[ii]
        ind = -1
        ((i)...(n)).reverse_each do |j|
          if(s[j] == pt[ii])
            ind = j
            break
          end
        end
        ans.push([ind+1,i+1])
        t[i], s[ind] = s[ind], t[i]
        next unless ind == -1
      end
      i += 1
    end
    puts "Yes"
    puts ans.size
    ans.size.times do |i|
      puts ans[i].join(" ")
    end
  else
    puts "No"
    next
  end
end

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

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

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

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

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

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

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

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

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

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

q = inp[0]
nt = []
st = []
tt = []
q.times do
  nt << inp[0]
  st << gets.chomp
  tt << gets.chomp
end
q.times do |i|
  n = nt[i]
  s = st[i]
  t = tt[i]
  m = na(27)
  m[-1] = 999999
  ao = "a".ord
  n.times do |i|
    m[s[i].ord - ao] += 1
    m[t[i].ord - ao] += 1
  end
  f = true
  26.times do |i|
    if m[i].odd?
      f = false
    end
  end
  at = ""

  mm = copy(m)
  mm.map{|d|d/2}
  if (f)
    ans = []
    n.times do |i|
      at += s[i]
      at += t[i]
    end
    pt = at
    pt = pt.split("").sort!.join("")
    i = 0
    while i < n
      ii = i*2
      if s[i] != pt[ii]
        ind = -1
        ((i)...(n)).reverse_each do |j|
          if(t[j] == pt[ii])
            ind = j
            break
          end
        end
        ans.push([i+1,ind+1]) unless ind == -1
        s[i], t[ind] = t[ind], s[i] unless ind == -1
        next unless ind == -1
      end
      if t[i] != pt[ii]
        ind = -1
        ((i)...(n)).reverse_each do |j|
          if(s[j] == pt[ii])
            ind = j
            break
          end
        end
        ans.push([ind+1,i+1]) unless ind == -1
        t[i], s[ind] = s[ind], t[i] unless ind == -1
        next unless ind == -1
      end
      i += 1
    end
    puts "Yes"
    puts ans.size
    ans.size.times do |i|
      puts ans[i].join(" ")
    end
  else
    puts "No"
    next
  end
end

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

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

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

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

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

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

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

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

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

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

q = inp[0]
nt = []
st = []
tt = []
q.times do
  nt << inp[0]
  st << gets.chomp
  tt << gets.chomp
end
q.times do |i|
  n = nt[i]
  s = st[i]
  t = tt[i]
  m = na(27)
  m[-1] = 999999
  ao = "a".ord
  n.times do |i|
    m[s[i].ord - ao] += 1
    m[t[i].ord - ao] += 1
  end
  f = true
  26.times do |i|
    if m[i].odd?
      f = false
    end
  end
  at = ""

  mm = copy(m)
  mm.map{|d|d/2}
  if (f)
    ans = []
    n.times do |i|
      at += s[i]
      at += t[i]
    end
    pt = at
    pt = pt.split("").sort!.join("")
    (n*2).times do |ii|
      i = ii/2
      if s[i] != pt[ii]
        ind = 0
        ((i)...(n)).each do |j|
          if(t[j] == pt[ii])
            ind = j
          end
        end
        ans.push([i+1,ind+1])
        s[i], t[ind] = t[ind], s[i]
      end
      if t[i] != pt[ii]
        ind = 0
        ((i)...(n)).each do |j|
          if(s[j] == pt[ii])
            ind = j
          end
        end
        ans.push([ind+1,i+1])
        t[i], s[ind] = s[ind], t[i]
      end
    end

    puts ans.size
    ans.size.times do |i|
      puts ans[i].join(" ")
    end
  else
    puts "No"
    next
  end
end

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

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

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

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

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

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

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

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

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

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

q = inp[0]
nt = []
st = []
tt = []
q.times do
  nt << inp[0]
  st << gets.chomp
  tt << gets.chomp
end
q.times do |i|
  n = nt[i]
  s = st[i]
  t = tt[i]
  m = na(27)
  m[-1] = 999999
  ao = "a".ord
  n.times do |i|
    m[s[i].ord - ao] += 1
    m[t[i].ord - ao] += 1
  end
  f = true
  26.times do |i|
    if m[i].odd?
      f = false
    end
  end
  at = ""

  mm = copy(m)
  mm.map{|d|d/2}
  if (f)
    ans = []
    n.times do |i|
      at += s[i]
      at += t[i]
    end
    pt = at
    pt = pt.split("").sort!.join("")
    (n*2).times do |ii|
      i = ii/2
      if s[i] != pt[ii]
        ind = 0
        ((i)...(n)).each do |j|
          if(t[j] == pt[ii])
            ind = j
          end
        end
        ans.push([i+1,ind+1])
        s[i], t[ind] = t[ind], s[i]
      end
      if t[i] != pt[ii]
        ind = 0
        ((i)...(n)).each do |j|
          if(s[j] == pt[ii])
            ind = j
          end
        end
        ans.push([ind+1,i+1])
        t[i], s[ind] = s[ind], t[i]
      end
    end
    puts "Yes"
    puts ans.size
    ans.size.times do |i|
      puts ans[i].join(" ")
    end
  else
    puts "No"
    next
  end
end

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

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

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

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

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

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

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

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

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

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

q = inp[0]
nt = []
st = []
tt = []
q.times do
  nt << inp[0]
  st << gets.chomp
  tt << gets.chomp
end
q.times do |i|
  n = nt[i]
  s = st[i]
  t = tt[i]
  m = na(27)
  m[-1] = 999999
  ao = "a".ord
  n.times do |i|
    m[s[i].ord - ao] += 1
    m[t[i].ord - ao] += 1
  end
  f = true
  26.times do |i|
    if m[i].odd?
      f = false
    end
  end
  at = ""

  mm = copy(m)
  mm.map{|d|d/2}
  if (f)
    ans = []
    n.times do |i|
      at += s[i]
      at += t[i]
    end
    pt = at
    pt = pt.split("").sort!.join("")
    i = 0
    while i < n
      ii = i*2
      if s[i] != pt[ii]
        ind = -1
        ((i)...(n)).reverse_each do |j|
          if(t[j] == pt[ii] )
            ind = j
            break if(t[j] != pt[j*2])
          end
        end
        ans.push([i+1,ind+1]) unless ind == -1
        s[i], t[ind] = t[ind], s[i] unless ind == -1
        next unless ind == -1
      end
      if t[i] != pt[ii]
        ind = -1
        ((i)...(n)).reverse_each do |j|
          if(s[j] == pt[ii] )
            ind = j
            break if(s[j] != pt[j*2])
          end
        end
        ans.push([ind+1,i+1]) unless ind == -1
        t[i], s[ind] = s[ind], t[i] unless ind == -1
        next unless ind == -1
      end
      i += 1
    end
    puts "Yes"
    puts ans.size
    ans.size.times do |i|
      puts ans[i].join(" ")
    end
  else
    puts "No"
    next
  end
end


The Two-dimensional kingdom is going through hard times... This morning the Three-Dimensional kingdom declared war on the Two-dimensional one. This (possibly armed) conflict will determine the ultimate owner of the straight line.The Two-dimensional kingdom has a regular army of n people. Each soldier registered himself and indicated the desired size of the bulletproof vest: the i-th soldier indicated size ai. The soldiers are known to be unpretentious, so the command staff assumes that the soldiers are comfortable in any vests with sizes from ai - x to ai + y, inclusive (numbers x, y ≥ 0 are specified). The Two-dimensional kingdom has m vests at its disposal, the j-th vest's size equals bj. Help mobilize the Two-dimensional kingdom's army: equip with vests as many soldiers as possible. Each vest can be used only once. The i-th soldier can put on the j-th vest, if ai - x ≤ bj ≤ ai + y.

The first input line contains four integers n, m, x and y (1 ≤ n, m ≤ 105, 0 ≤ x, y ≤ 109) — the number of soldiers, the number of vests and two numbers that specify the soldiers' unpretentiousness, correspondingly. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) in non-decreasing order, separated by single spaces — the desired sizes of vests.  The third line contains m integers b1, b2, ..., bm (1 ≤ bj ≤ 109) in non-decreasing order, separated by single spaces — the sizes of the available vests.

In the first line print a single integer k — the maximum number of soldiers equipped with bulletproof vests.  In the next k lines print k pairs, one pair per line, as "ui vi" (without the quotes). Pair (ui, vi) means that soldier number ui must wear vest number vi. Soldiers and vests are numbered starting from one in the order in which they are specified in the input. All numbers of soldiers in the pairs should be pairwise different, all numbers of vests in the pairs also should be pairwise different. You can print the pairs in any order. If there are multiple optimal answers, you are allowed to print any of them.

NoteIn the first sample you need the vests' sizes to match perfectly: the first soldier gets the first vest (size 1), the third soldier gets the second vest (size 3). This sample allows another answer, which gives the second vest to the fourth soldier instead of the third one.In the second sample the vest size can differ from the desired size by at most 2 sizes, so all soldiers can be equipped.

n,m,x,y = gets.split.map(&:to_i)
u = gets.split.map(&:to_i)
v = gets.split.map(&:to_i)

ans = 0
now = 0
v.each do |vest|
  while now < u.size && (u[now]+y < vest)
    now += 1
  end
  break if now == u.size
  if u[now]-x <= vest && vest <= u[now]+y
    ans+=1
    now+=1
  end
end
p ans

now = 0
tmp = 0
v.each do |vest|
  while now < u.size && (u[now]+y < vest)
    now += 1
  end
  break if now == u.size
  if u[now]-x <= vest && vest <= u[now]+y
    ans+=1
    now+=1
    puts "#{now} #{tmp+1}"
  end
  tmp += 1
end

n, m, x, y = gets.split.map(&:to_i)
a = gets.split.map(&:to_i)
b = gets.split.map(&:to_i)

res = []
j = 0
(0...n).each do |i|
  while j < m and b[j] <= a[i] + y do
    b[j] < a[i] - x ? j += 1 : break
  end
  break if j == m
  if a[i] - x <= b[j] and  b[j] <= a[i] + y
    res.push [i+1, j+1]
    j += 1
  end
end
puts res.size
res.each { |e| puts e*' ' }

# http://codeforces.com/problemset/problem/161/A
n, m, x, y = gets.chomp.split.map(&:to_i)
a = gets.chomp.split.map(&:to_i)
b = gets.chomp.split.map(&:to_i)

i, j = 0, 0
result = []

while i < n && j < m
  if b[j] >= a[i] - x && b[j] <= a[i] + y
    result << [i + 1, j + 1]
    i += 1
    j += 1
  elsif b[j] < a[i] + y
    j += 1
  else
    i += 1
  end
end

puts result.length
result.each do |pair|
  print pair[0], " ", pair[1], "\n"
end

n, m, x, y = gets.split.map(&:to_i)
a = gets.split.map(&:to_i)
b = gets.split.map(&:to_i)

res = []
(0...n).each do |i|
  res.push (0...m).find_all {|j| a[i]-x <= b[j] and b[j] <= a[i]+y }
end
taken = []
puts [res.flatten.uniq.size, m].min
res.each_with_index do |e, i|
  next if e.size.zero?
  jj = (0...e.size).find { |j| !taken.include?(e[j]) }
  next if jj.nil? or e[jj].nil?
  puts "#{i+1} #{e[jj]+1}"
  taken.push e[jj]
end


Petya and Vasya are brothers. Today is a special day for them as their parents left them home alone and commissioned them to do n chores. Each chore is characterized by a single parameter — its complexity. The complexity of the i-th chore equals hi.As Petya is older, he wants to take the chores with complexity larger than some value x (hi > x) to leave to Vasya the chores with complexity less than or equal to x (hi ≤ x). The brothers have already decided that Petya will do exactly a chores and Vasya will do exactly b chores (a + b = n).In how many ways can they choose an integer x so that Petya got exactly a chores and Vasya got exactly b chores?

The first input line contains three integers n, a and b (2 ≤ n ≤ 2000; a, b ≥ 1; a + b = n) — the total number of chores, the number of Petya's chores and the number of Vasya's chores. The next line contains a sequence of integers h1, h2, ..., hn (1 ≤ hi ≤ 109), hi is the complexity of the i-th chore. The numbers in the given sequence are not necessarily different. All numbers on the lines are separated by single spaces.

Print the required number of ways to choose an integer value of x. If there are no such ways, print 0.

NoteIn the first sample the possible values of x are 3, 4 or 5.In the second sample it is impossible to find such x, that Petya got 3 chores and Vasya got 4.

I = ->{gets.split.map(&:to_i)}
n, a, b = I[]
c = I[].sort
p c[b] - c[b - 1]

n, a, b = gets.split.collect{|i| i.to_i}
values = gets.split.collect{|i| i.to_i}.sort

if values[b-1] == values[b]
  puts 0
else
  puts values[b] - values[b-1]
end

# ProblemA.rb

n, a, b = gets.split().map {|s| s.to_i}
chores = gets.split().map {|s| s.to_i}

chores = chores.sort

vasya = chores[0...b]
petya = chores[b..-1]

if petya.index(vasya[-1]) || vasya.index(petya[0])
  puts "0"
  exit
end

puts petya[0] - vasya[-1]

n, a, b = gets.chomp.split.map(&:to_i)
list = gets.chomp.split.map(&:to_i).sort

list[n - a]
list[n - a - 1]

x = list[n - a] - list[n - a - 1]
puts x > 0 ? x : 0

s = gets.chomp.split(" ")
kolvo = s[0].to_i
a = s[1].to_i
b = s[2].to_i
p = gets.chomp.split(" ")
massiv = Array.new(kolvo){}
for i in(0..kolvo-1)
    massiv[i] = p[i].to_i
end
massiv = massiv.sort
if massiv[b]-massiv[b-1]!=0 then
    k = massiv[b]-massiv[b-1]
    puts k
else
    puts 0
end

def execute(n, a, b, h)
  h.sort! {|x, y| x <=> y }
  x = h[n - a] - h[b - 1]
end

# puts execute(5, 2, 3, %w(6 2 3 100 1).map(&:to_i))
# puts execute(7, 3, 4, %w(1 1 9 1 1 1 1).map(&:to_i))
n, a, b = gets.chomp.split(' ').map(&:to_i)
h = gets.chomp.split(' ').map(&:to_i)
puts execute(n, a, b, h)

n,a,b = gets.chomp.split(/ /).map!{|x| x.to_i}
h = gets.chomp.split(/ /).map!{|x| x.to_i}
h.sort!()
ret = h[b] - h[b-1]
puts ret

I = ->{gets.split.map(&:to_i)}
n, a, b = I[]
c = I[].sort
p c[b, a].min - c[0, b].max

def checks(n_a_b, h)
	n_a_b = n_a_b.split.map(&:to_i)
	n = n_a_b[0]
	a = n_a_b[1]
	b = n_a_b[2]

	h = h.split.map(&:to_i)

	h.sort!

	n_a = h.last(a)
	n_e = h.first(b)

	puts n_a.first - n_e.last
end

checks(gets, gets)

n,b,c=gets.chomp.split.map(&:to_i)
a=gets.chomp.split.map(&:to_i)
i=1
while i<n
	j=i-1
	while j>=0
		if a[j]<a[j+1]
			a[j],a[j+1]=a[j+1],a[j]
		end
		j-=1
	end
	i+=1
end
puts a[b-1]-a[b]

chore_number, petya_chore_number, vasya_chore_number = gets.split(' ').map(&:to_i)

chores = gets.split(' ').map(&:to_i).sort

puts chores[chore_number - petya_chore_number] - chores[vasya_chore_number - 1]

n, a, b = gets.rstrip.split(' ').map(&:to_i)
arr = gets.rstrip.split.map(&:to_i)

sorted_arr = arr.sort

b_last_chore = b - 1
b_chore = sorted_arr[b_last_chore]

a_chores = []
i = b_last_chore + 1
a.times do
  a_chores.push sorted_arr[i]
  i += 1
end

diff = a_chores.first - b_chore
puts diff

def chores
  chores = STDIN.gets.split(' ').map{|i| i.to_i}
  c = STDIN.gets.split(' ').map{|i| i.to_i}
  c.sort!

  max = c[c.size-chores[1]]

  n = max
  (c.size-chores[1]).downto(0) do |i|
    if c.select{|j| j > c[i]}.size > chores[1]
      break
    else
      n = c[i]
    end
  end
  puts max - n
end

#plant

chores

s = gets.chomp.split(" ")
kolvo = s[0].to_i
a = s[1].to_i
b = s[2].to_i
p = gets.chomp.split(" ")
massiv = Array.new(kolvo){}
for i in(0..kolvo-1)
    massiv[i] = p[i].to_i
end
massiv = massiv.sort
puts massiv
if massiv[b]-massiv[b-1]!=0 then
    k = massiv[b]-massiv[b-1]
    puts k
else
    puts 0
end

def execute(n, a, b, h)
  h.sort! {|x, y| x <=> y }
  puts h.inspect # [1, 2, 3, 6, 100]
  x = h[n - a] - h[b - 1]
end

# puts execute(5, 2, 3, %w(6 2 3 100 1).map(&:to_i))
# puts execute(7, 3, 4, %w(1 1 9 1 1 1 1).map(&:to_i))
n, a, b = gets.chomp.split(' ').map(&:to_i)
h = gets.chomp.split(' ').map(&:to_i)
puts execute(n, a, b, h)

def checks(n_a_b, h)
	n_a_b = n_a_b.split.map(&:to_i)
	n = n_a_b[0]
	a = n_a_b[1]
	b = n_a_b[2]

	h = h.split.map(&:to_i)

	h.sort!

	n_a = h.last(a)
	n_e = h.first(b)

	x = n_a.first - 1

	count = 0
	for i in (0..n - 1)
		if x < n_a.first && x >= n_e.last
			x -=1
		end
	end

	puts 4
end

checks(gets, gets)

def checks(n_a_b, h)
	n_a_b = n_a_b.split.map(&:to_i)
	n = n_a_b[0]
	a = n_a_b[1]
	b = n_a_b[2]

	h = h.split.map(&:to_i)

	h.sort!

	n_a = h.last(a)
	n_e = h.first(b)

	x = n_a.first - 1

	count = 0
	for i in (0..n - 1)
		if x < n_a.first && x >= n_e.last
			x -=1
			count += 1
		end
	end

	puts count
end

checks(gets, gets)

def checks(n_a_b, h)
	n_a_b = n_a_b.split.map(&:to_i)
	n = n_a_b[0]
	a = n_a_b[1]
	b = n_a_b[2]

	h = h.split.map(&:to_i)

	h.sort!

	puts h[n - a] - h[a]
end

checks(gets, gets)

def chores
  chores = STDIN.gets.split(' ').map{|i| i.to_i}
  c = STDIN.gets.split(' ').map{|i| i.to_i}
  c.sort!

  max = c[c.size-chores[1]]
  min = max

  (c.size-chores[1]).downto(0) do |i|
    if c[i] > min
      break
    else
      min -= 1
    end
  end
  puts max-min-1
end

chores


Given an array $$$a$$$ of length $$$n$$$, find another array, $$$b$$$, of length $$$n$$$ such that:  for each $$$i$$$ $$$(1 \le i \le n)$$$ $$$MEX(\{b_1$$$, $$$b_2$$$, $$$\ldots$$$, $$$b_i\})=a_i$$$. The $$$MEX$$$ of a set of integers is the smallest non-negative integer that doesn't belong to this set.If such array doesn't exist, determine this.

The first line contains an integer $$$n$$$ ($$$1 \le n \le 10^5$$$) — the length of the array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, $$$\ldots$$$, $$$a_n$$$ ($$$0 \le a_i \le i$$$) — the elements of the array $$$a$$$. It's guaranteed that $$$a_i \le a_{i+1}$$$ for $$$1\le i < n$$$.

If there's no such array, print a single line containing $$$-1$$$. Otherwise, print a single line containing $$$n$$$ integers $$$b_1$$$, $$$b_2$$$, $$$\ldots$$$, $$$b_n$$$ ($$$0 \le b_i \le 10^6$$$) If there are multiple answers, print any.

NoteIn the second test case, other answers like $$$[1,1,1,0]$$$, for example, are valid.

def ans(aa)
  bb = {}
  for v in aa
    bb[v] = 1
  end

  tt = []
  for v in (0..aa.length)
    bb[v].nil? and tt << v
  end

  t =aa.first
  ret = []
  ti = 0
  aa.each {|e|
    if e != t
      ret << t
    else
      ret << tt[ti]
      ti+=1
    end
    t =e
  }

  ret
end

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

def ans(aa)
  bb = {}
  for v in aa
    bb[v] = 1
  end

  tt = []
  for v in (0..aa.length)
    bb[v].nil? and tt << v
  end

  t = 0
  ret = []
  ti = 0
  aa.each {|e|
    if e != t
      ret << t
    else
      ret << tt[ti]
      ti+=1
    end
    t =e
  }

  ret
end

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

def ans(aa)
  ret = []
  v = aa.first
  vi = 0
  if aa.first == 0
    ret << 1
  elsif aa.first == 1
    ret << 0
  else
    return -1
  end
  retMax = ret.max
  aa.each_with_index {|e,i|
    if e != v
      ret[i]= v
      retMax = [retMax, v].max
      t = ret[vi]
      #printf("ret:%s i:%d e:%d\n", ret.to_s, i, e)
      if e-v >= i - vi
        t = v + 1
        t == e and t+=1
      end
      (vi+1...i).each { |j|
        ret[j] = [t, e-1].min
        retMax = [retMax, ret[j]].max
        t+=1
        t == e and t+=1
      }
      retMax < e-1 and return -1
      v = e
      vi = i
    end
  }

  while ret.length < aa.length
    ret << ret.last
  end
  return ret
end

gets
a = gets.chomp.split(" ").map &:to_i
puts ans(a)


Harry Potter is on a mission to destroy You-Know-Who's Horcruxes. The first Horcrux that he encountered in the Chamber of Secrets is Tom Riddle's diary. The diary was with Ginny and it forced her to open the Chamber of Secrets. Harry wants to know the different people who had ever possessed the diary to make sure they are not under its influence.He has names of n people who possessed the diary in order. You need to tell, for each person, if he/she possessed the diary at some point before or not.Formally, for a name si in the i-th line, output "YES" (without quotes) if there exists an index j such that si = sj and j < i, otherwise, output "NO" (without quotes).

First line of input contains an integer n (1 ≤ n ≤ 100) — the number of names in the list. Next n lines each contain a string si, consisting of lowercase English letters. The length of each string is between 1 and 100.

Output n lines each containing either "YES" or "NO" (without quotes), depending on whether this string was already present in the stream or not. You can print each letter in any case (upper or lower).

NoteIn test case 1, for i = 5 there exists j = 3 such that si = sj and j < i, which means that answer for i = 5 is "YES".

require 'set'

read = Set.new

gets.to_i.times do
	name = gets.chomp;

	puts read.include?(name) ? "YES" : "NO"

	read.add(name)
end

n = gets.to_i
s = [gets.chomp]
puts 'NO'
(n - 1).times do
  flag = FALSE
  t = gets.chomp
  s.each do |name|
    if t == name
      puts 'YES'
      flag = TRUE
      break
    end
  end
  if !flag
    puts 'NO'
    s << t
  end
end

h={}
gets.to_i.times{s=gets.chomp;puts h[s]?:YES: :NO;h[s]=1}

n = gets.to_i
names = []
n.times do
  s = gets.chomp
  if names.include?(s)
    puts 'YES'
  else
    puts 'NO'
  end
  names << s
end

n = gets.strip.to_i
list = {}
n.times do
    s = gets.strip
    if list.has_key? s
        puts "YES"
    else
        list[s] = 1
        puts "NO"
    end
end

n = gets.to_i
a = []
n.times do |i|
    s = gets.chomp
    if a.include?(s)
        puts "YES"
    else
        puts "NO"
        a.push(s)
    end
end

n = gets.to_i
name = {}
n.times do
    s = gets
    if name[s]
        puts 'YES'
    else
        puts 'NO'
        name[s] = true
    end
end

t = gets.chomp.to_i
arr = []
t.times do
	t = gets.chomp
	if arr.include? t
		puts "yes"
	else
		puts "no"
		arr << t
	end
end

n = gets

a={}
b=[]
for i in 0..n.to_i-1 do
    value = gets
    b[i]=value
end

for i in 0..n.to_i-1 do
    value = b[i]
    if a[value]
        print "YES"
        print "\n" if i!=n.to_i-1
    else
        print "NO"
        a[value]=1
        print "\n" if i!=n.to_i-1
    end
end

n = gets

a={}
for i in 1..n.to_i do
    value = gets
    if a[value]
        p "YES"
    else
        p "NO"
        a[value]=1
    end
end


Bob wants to put a new bargaining table in his office. To do so he measured the office room thoroughly and drew its plan: Bob's office room is a rectangular room n × m meters. Each square meter of the room is either occupied by some furniture, or free. A bargaining table is rectangular, and should be placed so, that its sides are parallel to the office walls. Bob doesn't want to change or rearrange anything, that's why all the squares that will be occupied by the table should be initially free. Bob wants the new table to sit as many people as possible, thus its perimeter should be maximal. Help Bob find out the maximum possible perimeter of a bargaining table for his office.

The first line contains 2 space-separated numbers n and m (1 ≤ n, m ≤ 25) — the office room dimensions. Then there follow n lines with m characters 0 or 1 each. 0 stands for a free square meter of the office room. 1 stands for an occupied square meter. It's guaranteed that at least one square meter in the room is free.

Output one number — the maximum possible perimeter of a bargaining table for Bob's office room.

n,m = gets.split.map(&:to_i)
r = Array.new(n){gets.split ''}
a = 4
for i in 0...n
for j in 0...m
    next if r[i][j]=='1'
    for ii in i...n
        break if r[ii][j]=='1'
per = 2*(2+ii-i)
a=per if per>a
        for jj in (j+1)...m
            break unless for iii in i..ii
                break if r[iii][jj]=='1'
            end
            per = 2*((1+ii-i)+(1+jj-j))
            a=per if per>a
        end
    end
end
end
p a

n, m = *gets.split(' ').map { |s| s.to_i }
a = []
n.times do
    a << gets.chomp
end

def ok?(a, x1, y1, x2, y2)
    x1.upto(x2) do |i|
        y1.upto(y2) do |j|
            return false if a[i][j] == ?1
        end
    end
    return true
end

perimeter = -1
0.upto(n-1) do |x2|
    0.upto(m-1) do |y2|
        0.upto(x2) do |x1|
            0.upto(y2) do |y1|
                p = x2+y2-x1-y1
                next if p <= perimeter
                next unless ok?(a, x1, y1, x2, y2)
                perimeter = p
            end
        end
    end
end

puts perimeter * 2 + 4

n,m = gets.split.map(&:to_i)
r = Array.new(n){gets.split ''}
a = 4
for i in 0...n
for j in 0...m
    next if r[i][j]=='1'
    for ii in (i+1)...n
        break if r[ii][j]=='1'
        for jj in (j+1)...m
            break unless for iii in i..ii
                break nil if r[iii][jj]=='1'
            end
            per = 2*((1+ii-i)+(1+jj-j))
            a=per if per>a
        end
    end
end
end
p a

n,m = gets.split.map(&:to_i)
r = Array.new(n){gets.split ''}
a = 4
for i in 0...n
for j in 0...m
    next if r[i][j]=='1'
    for ii in (i+1)...n
per = 2*((1+ii-i)+1)
a=per if per>a
        break if r[ii][j]=='1'
        for jj in (j+1)...m
            break unless for iii in i..ii
                break nil if r[iii][jj]=='1'
            end
            per = 2*((1+ii-i)+(1+jj-j))
            a=per if per>a
        end
    end
end
end
p a


Vanya has a table consisting of 100 rows, each row contains 100 cells. The rows are numbered by integers from 1 to 100 from bottom to top, the columns are numbered from 1 to 100 from left to right. In this table, Vanya chose n rectangles with sides that go along borders of squares (some rectangles probably occur multiple times). After that for each cell of the table he counted the number of rectangles it belongs to and wrote this number into it. Now he wants to find the sum of values in all cells of the table and as the table is too large, he asks you to help him find the result.

The first line contains integer n (1 ≤ n ≤ 100) — the number of rectangles. Each of the following n lines contains four integers x1, y1, x2, y2 (1 ≤ x1 ≤ x2 ≤ 100, 1 ≤ y1 ≤ y2 ≤ 100), where x1 and y1 are the number of the column and row of the lower left cell and x2 and y2 are the number of the column and row of the upper right cell of a rectangle.

In a single line print the sum of all values in the cells of the table.

NoteNote to the first sample test:Values of the table in the first three rows and columns will be as follows:121121110So, the sum of values will be equal to 10.Note to the second sample test:Values of the table in the first three rows and columns will be as follows:222222222So, the sum of values will be equal to 18.

n = gets.to_i
result = 0
n.times do
   x1, y1, x2, y2 = gets.split.map(&:to_i)
   result += (x2 - x1 + 1) * (y2 - y1 + 1)
end

p result

# http://codeforces.com/contest/552/problem/A
n = gets.chomp.to_i
hash = Hash.new(0)
n.times do
  x1, y1, x2, y2 = gets.chomp.split.map(&:to_i)
  (x1..x2).each do |x|
    (y1..y2).each do |y|
      hash[[x, y]] += 1
    end
  end
end

puts hash.values.inject(0) { |a, e| a + e }

#!/usr/bin/ruby
# ==> Made With LOVE <3 <==

n = gets.to_i
sum=0

n.times do
	x1, x2, y1, y2 = gets.split.map(&:to_i)
	sum += (y1 - x1 + 1) * (y2 - x2 + 1)
end

puts sum

rectangleNum = gets.chomp.to_i
rectangle = []

(0...rectangleNum).each do |iter|
	rectangle << gets.chomp.split(' ').map {|item| item.to_i}
end

result = 0
rectangle.each do |rec|
	result += (rec[2] - rec[0] + 1) * (rec[3] - rec[1] + 1)
end

puts result

a=gets.chomp.to_i
b=[]
a.times do
temp=gets.chomp.split(" ")
c=(temp[2].to_i-temp[0].to_i+1)*(temp[3].to_i-temp[1].to_i+1)
b<<c
end
ans=0
b.each {|i| ans=ans+i}
puts "#{ans}"

ans=0
gets.to_i.times{|e|
	x1,y1,x2,y2=gets.split.map{|e| e.to_i}
	ans+=((x1-x2).abs+1)*((y1-y2).abs+1)
}
puts ans

n = gets.to_i
ans = n.times.map do |i;x1,x2,y1,y2|
	x1,y1,x2,y2 = gets.split.map(&:to_i)
	(x2 - x1 + 1) * (y2 - y1 + 1)
end
puts ans.reduce(:+)

n = gets.to_i
d = n.times.map{gets.split.map(&:to_i)}
table = Array.new(100){Array.new(100){0}}
d.each do |x1,y1,x2,y2|
    i = x1
    while(i <= x2)
        j = y1
        while(j <= y2)
            table[j-1][i-1] += 1
            j+=1
        end
        i+=1
    end
end
p table.flatten.reduce(&:+)

n = gets.to_i
ans = 0
n.times do
    x1, y1, x2, y2 = gets.split.collect{|i| i.to_i}
    ans += (x2-x1+1)*(y2-y1+1)
end
puts ans

n = gets.to_i
ans = 0
n.times do
  a, b, c, d = gets.split.map(&:to_i)
  ans += (c - a + 1) * (d - b + 1)
end
puts ans

#!/usr/bin/env ruby

num = ARGF.gets.chomp.to_i
count = 0

num.times do
    x1, y1, x2, y2 = ARGF.gets.chomp.split(' ').map { |s| s.to_i }
    count += (y2 - y1 + 1) * (x2 - x1 + 1)
end

puts count

n = gets().chomp().to_i
count = 0
n.times do
        x1, y1, x2, y2= gets().split(' ').map{ |p| p.to_i}

        count += (y2 - y1 +1) *(x2-x1+1)
end
puts count

n = gets.to_i
ans = 0
n.times do
	x1, y1, x2, y2 = gets.split.map { |x| x.to_i }
	ans += (x2 - x1 + 1) * (y2 - y1 + 1)
end
puts ans

rectangleNum = gets.chomp.to_i

firstRec = gets.chomp.split(' ').map {|item| item.to_i}
secondRec = gets.chomp.split(' ').map {|item| item.to_i}

result = 0

maxX = if firstRec[2] > secondRec[2]
	firstRec[2]
else
	secondRec[2]
end

maxY = if firstRec[3] > secondRec[3]
	firstRec[3]
else
	secondRec[3]
end

(1..maxY).each do |y|
	(1..maxX).each do |x|
		if x >= firstRec[0] && x <= firstRec[2] && y >= firstRec[1] && y <= firstRec[3]
			result += 1
		end

		if x >= secondRec[0] && x <= secondRec[2] && y >= secondRec[1] && y <= secondRec[3]
			result += 1
		end
	end
end

puts result


Define the score of some binary string $$$T$$$ as the absolute difference between the number of zeroes and ones in it. (for example, $$$T=$$$ 010001 contains $$$4$$$ zeroes and $$$2$$$ ones, so the score of $$$T$$$ is $$$|4-2| = 2$$$).Define the creepiness of some binary string $$$S$$$ as the maximum score among all of its prefixes (for example, the creepiness of $$$S=$$$ 01001 is equal to $$$2$$$ because the score of the prefix $$$S[1 \ldots 4]$$$ is $$$2$$$ and the rest of the prefixes have a score of $$$2$$$ or less).Given two integers $$$a$$$ and $$$b$$$, construct a binary string consisting of $$$a$$$ zeroes and $$$b$$$ ones with the minimum possible creepiness.

The first line contains a single integer $$$t$$$ $$$(1\le t\le 1000)$$$  — the number of test cases. The description of the test cases follows. The only line of each test case contains two integers $$$a$$$ and $$$b$$$ ($$$ 1 \le a, b \le 100$$$)  — the numbers of zeroes and ones correspondingly.

For each test case, print a binary string consisting of $$$a$$$ zeroes and $$$b$$$ ones with the minimum possible creepiness. If there are multiple answers, print any of them.

NoteIn the first test case, the score of $$$S[1 \ldots 1]$$$ is $$$1$$$, and the score of $$$S[1 \ldots 2]$$$ is $$$0$$$.In the second test case, the minimum possible creepiness is $$$1$$$ and one of the other answers is 101.In the third test case, the minimum possible creepiness is $$$3$$$ and one of the other answers is 0001100.

gets.to_i.times do
  a, b = gets.split.map(&:to_i)

  s = ""
  while a + b > 0
    if a > 0
      s += '0'
      a -= 1
    end

    if b > 0
      s += '1'
      b -= 1
    end
  end

  puts s
end

gets.to_i.times do
  a, b = gets.split.map(&:to_i)
  d = [(a - b).abs, 1].max

  s = ""
  while a + b > 0
    ta = a - [a - d, 0].max
    tb = b - [b - d, 0].max
    s += '0' * ta
    s += '1' * tb
    a -= ta
    b -= tb
  end

  puts s
end

gets.to_i.times do
  a, b = gets.split.map(&:to_i)
  if a > b
    puts "10" * b + "0" * (a - b)
  else
    puts "01" * a + "1" * (b - a)
  end
end

# gets.to_i
# gets.split.map(&:to_i)

gets.to_i.times do
  a, b = gets.split.map(&:to_i)
  if a > b
    ans = Array.new(a+b, 0)
    i = 0
    while b > 0
      ans[i] = 1
      i += 2
      b -= 1
    end
  else
    ans = Array.new(a+b, 1)
    i = 0
    while a > 0
      ans[i] = 0
      i += 2
      a -= 1
    end
  end

  puts ans.join
end


There are two sisters Alice and Betty. You have $$$n$$$ candies. You want to distribute these $$$n$$$ candies between two sisters in such a way that:  Alice will get $$$a$$$ ($$$a > 0$$$) candies;  Betty will get $$$b$$$ ($$$b > 0$$$) candies;  each sister will get some integer number of candies;  Alice will get a greater amount of candies than Betty (i.e. $$$a > b$$$);  all the candies will be given to one of two sisters (i.e. $$$a+b=n$$$). Your task is to calculate the number of ways to distribute exactly $$$n$$$ candies between sisters in a way described above. Candies are indistinguishable.Formally, find the number of ways to represent $$$n$$$ as the sum of $$$n=a+b$$$, where $$$a$$$ and $$$b$$$ are positive integers and $$$a>b$$$.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 only line of a test case contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^9$$$) — the number of candies you have.

For each test case, print the answer — the number of ways to distribute exactly $$$n$$$ candies between two sisters in a way described in the problem statement. If there is no way to satisfy all the conditions, print $$$0$$$.

NoteFor the test case of the example, the $$$3$$$ possible ways to distribute candies are:  $$$a=6$$$, $$$b=1$$$;  $$$a=5$$$, $$$b=2$$$;  $$$a=4$$$, $$$b=3$$$.

t = gets.chomp.to_i
t.times do
  n = gets.chomp.to_i
  n-=1 if n%2 == 0
  puts n/2
end

gets.to_i.times do
	n = gets.to_i
	puts (n - 1) / 2
end

t = gets.to_i
t.times do
	n = gets.to_i
	puts n-n/2-1
end

t = gets.to_i
for i in 1..t do
  n = gets.to_i
  puts n - (n/2 + 1)
end

file = File.exist?('in.in') ? File.new('in.in','r') : STDIN

t = file.gets.to_i

while t != 0
  n = file.gets.to_i
  ans = n / 2
  if ans == 0 || ans == 1
    puts n == 2 ? 0 : ans
  else
    res = if n.even?
      (ans - 1) <= 0 ? 0 : ans-1
    else
      ans
    end
    puts res
  end
  t -= 1
end

t = gets.chomp.to_i

(1..t).each{
    n = gets.chomp.to_i

    puts (n-1)/2
}

# https://codeforces.com/problemset/problem/1335/A
def solution(n)
  return (n / 2.0).ceil - 1
end

t = gets.chomp.to_i

while t > 0 do
  puts solution(gets.chomp.to_i)
  t -= 1
end

gets.to_i.times do
  n = gets.to_i
  puts (n - 1)/2
end

t = gets.to_i

1.upto(t) do
  n = gets.to_i
  puts n.div(2) - 1 + n.modulo(2)
end

t = gets.to_i
(1).upto(t) do
  n = gets.to_i
  puts (n-1)/2
end

file = File.exist?('in.in') ? File.new('in.in','r') : STDIN

t = file.gets.to_i

while t != 0
  n = file.gets.to_i
  ans = n / 2
  if ans == 0 || ans == 1
    puts n == 2 ? 0 : ans
  else
    res = if ans.even?
      (ans - 1) <= 0 ? 0 : ans-1
    else
      ans
    end
    puts res
  end
  t -= 1
end

file = File.exist?('in.in') ? File.new('in.in','r') : STDIN

t = file.gets.to_i

while t != 0
  n = file.gets.to_i
  ans = n / 2
  res = if ans.even?
    (ans - 1) <= 0 ? 0 : ans-1
  else
    ans
  end
  puts res
  t -= 1
end


In the snake exhibition, there are $$$n$$$ rooms (numbered $$$0$$$ to $$$n - 1$$$) arranged in a circle, with a snake in each room. The rooms are connected by $$$n$$$ conveyor belts, and the $$$i$$$-th conveyor belt connects the rooms $$$i$$$ and $$$(i+1) \bmod n$$$. In the other words, rooms $$$0$$$ and $$$1$$$, $$$1$$$ and $$$2$$$, $$$\ldots$$$, $$$n-2$$$ and $$$n-1$$$, $$$n-1$$$ and $$$0$$$ are connected with conveyor belts.The $$$i$$$-th conveyor belt is in one of three states:  If it is clockwise, snakes can only go from room $$$i$$$ to $$$(i+1) \bmod n$$$.  If it is anticlockwise, snakes can only go from room $$$(i+1) \bmod n$$$ to $$$i$$$.  If it is off, snakes can travel in either direction.   Above is an example with $$$4$$$ rooms, where belts $$$0$$$ and $$$3$$$ are off, $$$1$$$ is clockwise, and $$$2$$$ is anticlockwise.Each snake wants to leave its room and come back to it later. A room is returnable if the snake there can leave the room, and later come back to it using the conveyor belts. How many such returnable rooms are there?

Each test contains multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \le t \le 1000$$$): the number of test cases. The description of the test cases follows.   The first line of each test case description contains a single integer $$$n$$$ ($$$2 \le n \le 300\,000$$$): the number of rooms.  The next line of each test case description contains a string $$$s$$$ of length $$$n$$$, consisting of only '<', '>' and '-'.   If $$$s_{i} = $$$ '>', the $$$i$$$-th conveyor belt goes clockwise.  If $$$s_{i} = $$$ '<', the $$$i$$$-th conveyor belt goes anticlockwise.  If $$$s_{i} = $$$ '-', the $$$i$$$-th conveyor belt is off.  It is guaranteed that the sum of $$$n$$$ among all test cases does not exceed $$$300\,000$$$.

For each test case, output the number of returnable rooms.

NoteIn the first test case, all rooms are returnable except room $$$2$$$. The snake in the room $$$2$$$ is trapped and cannot exit. This test case corresponds to the picture from the problem statement. In the second test case, all rooms are returnable by traveling on the series of clockwise belts.

t = gets.to_i
ans = []
t.times do
  n = gets.to_i
  str = gets.chomp.split("")
  hash = Hash.new(0)
  right = false
  left = false
  for i in 0..n-1
    if str[i] == ">"
      right = true
    elsif str[i] == "<"
      left = true
    else
      hash[i] = 1
      hash[(i+1)%n] = 1
    end
  end
  if right && left
    ans << hash.size()
  else
    ans << n
  end
end
ans.each do |v|
  puts v
end

t = gets.to_i
ans = []
t.times do
  n = gets.to_i
  str = gets.chomp.split("")
  str << str[0]
  cnt = n
  for i in 0..n-1
    cnt -= 1 if str[i] == ">" && str[i+1] == "<"
  end
  cnt = 0 if cnt == 1
  ans << cnt
end
ans.each do |v|
  puts v
end

t = gets.to_i
ans = []
t.times do
  n = gets.to_i
  str = gets.chomp.split("")
  cnt = n
  for i in 0..n-1
    cnt -= 1 if (str[i-1] == ">" && str[i] == "<") || (str[i-1] == "<" && str[i] == ">")
  end
  ans << cnt
end
ans.each do |v|
  puts v
end

t = gets.to_i
ans = []
t.times do
  n = gets.to_i
  str = gets.chomp.split("")
  hash = Hash.new(0)
  right = false
  left = false
  for i in 0..n-1
    if str[i] == ">"
      right = true
    elsif str[i] == "<"
      left = true
    else
      hash[i] = 1
      hash[(i+1)%(n-1)] = 1
    end
  end
  if right && left
    ans << hash.size()
  else
    ans << n
  end
end
ans.each do |v|
  puts v
end


One day, as Sherlock Holmes was tracking down one very important criminal, he found a wonderful painting on the wall. This wall could be represented as a plane. The painting had several concentric circles that divided the wall into several parts. Some parts were painted red and all the other were painted blue. Besides, any two neighboring parts were painted different colors, that is, the red and the blue color were alternating, i. e. followed one after the other. The outer area of the wall (the area that lied outside all circles) was painted blue. Help Sherlock Holmes determine the total area of red parts of the wall.Let us remind you that two circles are called concentric if their centers coincide. Several circles are called concentric if any two of them are concentric.

The first line contains the single integer n (1 ≤ n ≤ 100). The second line contains n space-separated integers ri (1 ≤ ri ≤ 1000) — the circles' radii. It is guaranteed that all circles are different.

Print the single real number — total area of the part of the wall that is painted red. The answer is accepted if absolute or relative error doesn't exceed 10 - 4.

NoteIn the first sample the picture is just one circle of radius 1. Inner part of the circle is painted red. The area of the red part equals π × 12 = π.In the second sample there are three circles of radii 1, 4 and 2. Outside part of the second circle is painted blue. Part between the second and the third circles is painted red. Part between the first and the third is painted blue. And, finally, the inner part of the first circle is painted red. Overall there are two red parts: the ring between the second and the third circles and the inner part of the first circle. Total area of the red parts is equal (π × 42 - π × 22) + π × 12 = π × 12 + π = 13π

n = gets.to_i
a = Array.new
s = gets.split(' ')
for i in 0..n-1
  a[i] = s[i].to_i
end
a = a.sort
a = a.reverse
ans = 0
0.step(n-2, 2) { |i|
  ans += a[i] * a[i] - a[i+1] * a[i+1]
}
if n % 2 == 1
  ans += a[n-1] * a[n-1]
end
puts ans * Math::PI

n = gets.to_i
a = gets.split.map(&:to_i).sort.reverse
ans = 0
0.step(n-2, 2) { |i|
  ans += a[i] * a[i] - a[i+1] * a[i+1]
}
ans += a[n-1] * a[n-1] if n % 2 == 1
p ans * Math::PI

def area rad
	Math::PI * rad * rad
end

n = STDIN.gets.chomp.to_i
radius = STDIN.gets.chomp.split(' ').map{|ch| ch.to_i}.sort
total = 0.0
num = 0
(n - 1).downto(0).each do |i|
	if num % 2 == 0
		total += area radius[i]
	else
		total -= area radius[i]
	end
	num += 1
end

puts total

def area rad
	Math::PI * rad * rad
end

n = STDIN.gets.chomp.to_i
radius = STDIN.gets.chomp.split(' ').map{|ch| ch.to_i}.sort
total = 0.0
num = 0
(n - 1).downto(0).each do |i|
	total += (num % 2 == 0) ? area(radius[i]) : -(area radius[i])
	num += 1
end

puts total

n = gets.to_i
r = gets.split.map &:to_i
r << 0 if r.size.odd?
s = 0
r.sort.each_slice(2) do |x, y|
  s += y**2 - x**2
end
p s * Math::PI

n = gets.to_i
rads = gets.split.map{|i| i.to_i}.sort

s = 0
if rads.size % 2 == 0 then
    i = 0
    while 2*i < rads.size do
        s += (rads[2*i+1]**2 - rads[2*i]**2)
        i += 1
    end
else
    i = 1
    s += rads[0]**2
    while 2*i < rads.size
        s += (rads[2*i]**2 - rads[2*i-1]**2)
        i += 1
    end
end

s *= Math::PI

puts s

gets
p Math::PI * gets.split.map{|_| _.to_f ** 2}.sort.inject{|i, j| j - i}

n = gets.to_i
r = gets.split.map(&:to_i).sort.reverse

back = 0
ans = 0
r.each do |x|
        if back<x
                ans += x*x
                back = x
        else
                ans -= x*x
                back = 0
        end
end
p ans*3.14159265358979323846

n = gets.chomp.to_i
r = gets.chomp.split(" ").map{|e| e.to_i}
r.sort!{|a, b| -(a <=> b)}

sum = 0.0
for i in 0..(n - 1) do
  if (i % 2 != 0)
    next
  end

  if (i + 1 >= n)
    sum += r[i] ** 2 * Math::PI
  else
    sum += (r[i] ** 2 - r[i + 1] ** 2) * Math::PI
  end
end
puts sum

n=gets.to_i
r=gets.chomp.split.map(&:to_i).sort.reverse
i,sign,ans=0,1,0
while i<n
	ans+=sign*r[i]*r[i]
	i+=1
	sign*=-1
end
puts 3.1415926536*ans

n = gets.to_i
a = gets.split.map(&:to_i)
s = a.sort!.reverse!.map! {|x| x**2 }.each_index { |i| a[i] *= -1 if i.odd? }.inject(:+)
puts s *= Math::PI

n = gets.to_i

a = gets.split.map &:to_f
a.sort!

ans = a.inject(0) do |x,y|
    y*y - x
end

p Math::PI * ans

n = gets.to_i
sum = 0

arr = gets.split(" ").map(&:to_i).sort
area = arr.map { |e| e * e * Math::PI }

if n.even?
	start = 1
else
	sum += area[0]
	start = 2
end

(start..(n-1)).step(2).each do |i|
	sum += area[i] - area[i-1]
end
puts sum

n = gets.to_i
r = gets.split.collect{|i| i.to_i}.sort.reverse
r.push(0)
ans = 0
for i in (0...n).step(2)
    ans += Math::PI*(r[i]*r[i]-r[i+1]*r[i+1])
end
puts ans

n = gets.to_i
r = gets.split.collect{|i| i.to_i}.sort.reverse
r.push(0)
ans = 0
outer_r = r[0]
color = 'r'
r[1,n].each do |inner_r|
    if color == 'r'
        ans += Math::PI*(outer_r*outer_r-inner_r*inner_r)
        color = 'g'
    else
        color = 'r'
    end
    outer_r = inner_r
end
puts ans

n  = gets.chomp.to_i
r  = gets.split.collect{|x| x.to_f}.sort
pi = 3.1415926
red = 0
(0..n-1).each{|i|
  if i % 2 == n % 2
    red -= (pi * r[i] * r[i])
  else
    red += (pi * r[i] * r[i])
  end
}

puts red

n=gets.to_i
a=gets.chomp.scan(/\w+/)
for i in 0..n-1 do
  a[i]=a[i].to_i
end
a.sort!
a.reverse!
k=0
for i in 0..n-1 do
  (i%2==0)?k+=(Math::PI)*a[i]*a[i]:k-=(Math::PI)*a[i]*a[i]
end
puts k

n = gets.to_i
radii = gets.split.map{|e| e.to_f}
radii.sort!.reverse!

PI = 3.141592653589793238462643

red = 0.0
prev = true
for i in 0..n-1
	if prev
		red += (radii[i] * radii[i] * PI)
		prev = false
	else
		red -= (radii[i] * radii[i] * PI)
		prev = true
	end
end

puts red

n = gets.to_i
a = gets.split.map { |x| x.to_i }.sort
m = a.size % 2
s = 0
for i in (n - 1).step(m + 1, -2)
  s += a[i] ** 2 - a[i - 1] ** 2
end
s += a[0] ** 2 if m == 1
puts(s * Math::PI)

gets
lists = gets.split.map(&:to_i).sort.reverse

sum = 0
lists.each_with_index do |v, i|
  sum += (i % 2 == 0) ? v * v : - v * v
end

puts (sum * Math::PI)

n = gets.to_i
radii = gets.split(" ").map{|e| e.to_i}

radii.sort!

area = 0
red = true
for i in 0...(n-1)
  if red
    curr = radii[n - 1 - i]
    prev = radii[n - 2 - i]
    diff = Math::PI * curr * curr - Math::PI * prev * prev
    area += diff
  end
  red = !red
end

if red
  area += Math::PI * radii[0] * radii[0]
end

puts area

gets
p gets.split.map { |i| i.to_i }.sort! { |a, b| b<=>a }.map { |r| Math::PI*r*r }.each_with_index.inject(0){ |sum, (value,index)| index.even? ? sum + value : sum - value }

gets
p Math::PI * gets.split.map{|_| _.to_f ** 2}.sort.reverse.inject{|i, j| j - i}

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

back = 0
ans = 0
r.each do |x|
        if back<x
                ans += x*x
                back = x
        else
                ans -= x*x
                back = 0
        end
end
p ans*3.14159265358979323846

n=gets.to_i
a=gets.chomp.scan(/\w+/)
for i in 0..n-1 do
  a[i]=a[i].to_i
end
a.sort!
k=0
for i in 0..n-1 do
  (i%2==0)?k+=(Math::PI)*a[i]*a[i]:k-=(Math::PI)*a[i]*a[i]
end
puts k

gets
lists = gets.split.map(&:to_i).sort.reverse

sum = 0
lists.each_with_index do |v, i|
  p sum
  sum += (i % 2 == 0) ? v * v : - v * v
end
p lists
p sum
puts (sum * Math::PI)

n = gets.to_i
radii = gets.split(" ").map{|e| e.to_i}

radii.sort!

area = 0
red = true
for i in 0...(n-1)
  if red
    curr = radii[n - 1 - i]
    prev = radii[n - 2 - i]
    puts curr
    puts prev
    diff = Math::PI * curr * curr - Math::PI * prev * prev
    area += diff
  end
  red = !red
end

if red
  area += Math::PI * radii[0] * radii[0]
end

puts area


You are given an integer sequence $$$a_1, a_2, \dots, a_n$$$.Find the number of pairs of indices $$$(l, r)$$$ ($$$1 \le l \le r \le n$$$) such that the value of median of $$$a_l, a_{l+1}, \dots, a_r$$$ is exactly the given number $$$m$$$.The median of a sequence is the value of an element which is in the middle of the sequence after sorting it in non-decreasing order. If the length of the sequence is even, the left of two middle elements is used.For example, if $$$a=[4, 2, 7, 5]$$$ then its median is $$$4$$$ since after sorting the sequence, it will look like $$$[2, 4, 5, 7]$$$ and the left of two middle elements is equal to $$$4$$$. The median of $$$[7, 1, 2, 9, 6]$$$ equals $$$6$$$ since after sorting, the value $$$6$$$ will be in the middle of the sequence.Write a program to find the number of pairs of indices $$$(l, r)$$$ ($$$1 \le l \le r \le n$$$) such that the value of median of $$$a_l, a_{l+1}, \dots, a_r$$$ is exactly the given number $$$m$$$.

The first line contains integers $$$n$$$ and $$$m$$$ ($$$1 \le n,m \le 2\cdot10^5$$$) — the length of the given sequence and the required value of the median. The second line contains an integer sequence $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 2\cdot10^5$$$).

N, M = gets.split.map(&:to_i)
as = gets.split.map(&:to_i)

ans = {}

[M, M+1].each do |d|
    sums = Hash.new(0)
    sums[0] = 1
    sum = 0
    acum = 0
    result = 0
    as.each do |a|
        x = a < d ? -1 : 1
        if x == 1
            acum += sums[sum]
        else
            acum -= sums[sum-1]
        end
        sum += x
        sums[sum] += 1
        result += acum
    end
    ans[d] = result
end
puts ans[M] - ans[M+1]


A bracket sequence is a string, containing only characters "(", ")", "[" and "]".A correct bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()[]", "([])" are correct (the resulting expressions are: "(1)+[1]", "([1+1]+1)"), and "](" and "[" are not. The empty string is a correct bracket sequence by definition.A substring s[l... r] (1 ≤ l ≤ r ≤ |s|) of string s = s1s2... s|s| (where |s| is the length of string s) is the string slsl + 1... sr. The empty string is a substring of any string by definition.You are given a bracket sequence, not necessarily correct. Find its substring which is a correct bracket sequence and contains as many opening square brackets «[» as possible.

The first and the only line contains the bracket sequence as a string, consisting only of characters "(", ")", "[" and "]". It is guaranteed that the string is non-empty and its length doesn't exceed 105 characters.

In the first line print a single integer — the number of brackets «[» in the required bracket sequence. In the second line print the optimal sequence. If there are more than one optimal solutions print any of them.

#!/usr/bin/ruby

s = STDIN.readline.strip + '$'
parens, brackets = [], []
left, right = 0, 0
best_count = 0
best_left, best_right = 1, 0
while right < s.length
	ch = s[right]
	error = false
	if ch == '('
		parens.push(right)
	elsif ch == '['
		brackets.push(right)
	elsif ch == ')'
		if parens.length == 0
			error = true
		elsif brackets.length != 0 and brackets[-1] > parens[-1]
			error = true
		else
			parens.pop
		end
	elsif ch == ']'
		if brackets.length == 0
			error = true
		elsif parens.length != 0 and parens[-1] > brackets[-1]
			error = true
		else
			brackets.pop
		end
	else
		error = true
	end
	if not error
		right += 1
	else
		next_left = right+1
		seek = right = right-1
		b, p, count = 0, 0, 0
		while seek >= left
			ch = s[seek]
			if ch == '['
				b -= 1
				count += 1
			elsif ch == ']'
				b += 1
			elsif ch == '('
				p -= 1
			elsif ch == ')'
				p += 1
			end
			if b == 0 and p == 0 and count > best_count
				best_count, best_left, best_right = count, seek, right
			end
			if b < 0 or p < 0
				b, p, count = 0, 0, 0
				right = seek-1
			end
			seek -= 1
		end
		parens, brackets = [], []
		left = right = next_left
	end
end
puts best_count
puts s[best_left..best_right]

#!/usr/bin/ruby

s = STDIN.readline.strip + '$'
parens, brackets = [], []
left, right = 0, 0
count, best_count = 0, 0
best_left, best_right = 1, 0
while right < s.length
	#puts 'left = %d, right = %d, count = %d, brackets = %s, parens = %s' % [
	#		left, right, count, brackets, parens]
	ch = s[right]
	error = false
	if ch == '('
		parens.push(right)
	elsif ch == '['
		brackets.push(right)
		count += 1
	elsif ch == ')'
		if parens.length == 0
			error = true
		elsif brackets.length != 0 and brackets[-1] > parens[-1]
			error = true
		else
			parens.pop
		end
	elsif ch == ']'
		if brackets.length == 0
			error = true
		elsif parens.length != 0 and parens[-1] > brackets[-1]
			error = true
		else
			brackets.pop
		end
	else
		error = true
	end
	if not error
		if parens.length == 0 and brackets.length == 0
			if count > best_count
				best_count, best_left, best_right = count, left, right
			end
		end
		right += 1
	else
		next_left = right+1

		# find the longest correct substring preceding the error
		right -= 1
		seek = right
		b, p, count = 0, 0, 0
		while seek >= left
			ch = s[seek]
			if ch == '['
				b -= 1
				count += 1
			elsif ch == ']'
				b += 1
			elsif ch == '('
				p -= 1
			elsif ch == ')'
				p += 1
			end
			if b == 0 and p == 0 and count > best_count
				best_count, best_left, best_right = count, seek, right
			end
			if b < 0 or p < 0
				b, p, count = 0, 0, 0
				right = seek-1
			end
			seek -= 1
		end

		parens, brackets = [], []
		left = right = next_left
		count = 0
	end
end
puts best_count
puts s[best_left..best_right]

A,B,C,D=[?[,?],?(,?)].map(&:ord)
def match(c,d)
	return 1 if (c==A)&&(d==B)
	return 0 if (c==C)&&(d==D)
	false
end
t=gets.chomp
s=t.bytes.each_with_index.map.to_a
size=s.size
table=Array.new(size+1)
stack=[]
s.each{|chr|
	ord,idx=chr
	if (ord==A)||(ord==C)||stack.empty?
		stack.push chr
	else
		if m=match(stack.last.first,ord)
			_ord,_idx=stack.pop
			table[idx]=0
			table[_idx]=m
		else
			stack.push chr
		end
	end
}
max=0
sum=0
_l=l=r=0
table.each_with_index{|n,idx|
	if n
		sum+=n
	else
		if sum>max
			max=sum
			l=_l
			r=idx-1
		end
		sum=0
		_l=idx+1
	end
}
puts max
puts max==0 ? "" : t[l..r]

s = gets.chomp
st = []
seq = []
rev = {}
rev[')'] = '('
rev[']'] = '['
i = 0
s.each_char do |c|
    if (c == '(' || c == '[')
        st.push([i, c])
    elsif (st.size() > 0 && (c == ')' || c == ']') && rev[c] == st.last[1])
        seq.push(st.last)
        seq.push([i, c])
        st.pop
    else
        while (st.size() > 0)
            st.pop
        end
    end
    i += 1
end
seq.sort!
res = "", mx = -1, prv = -1, c = 0, t = ""
for i in seq
    if (i[0] - prv == 1)
        c += 1 if (i[1] == '[')
        t.concat(i[1])
    else
        if (mx < c)
            mx = c
            res = t.dup
        end
        t.clear
        c = 0
        c += 1 if (i[1] == '[')
        t.concat(i[1])
    end
    prv = i[0]
end

if (mx < c)
    mx = c
    res = t.dup
end
puts mx, res

s = gets.chomp
st = []
seq = []
rev = {}
rev[')'] = '('
rev[']'] = '['
i = 0
s.each_char do |c|
    if (c == '(' || c == '[')
        st.push([i, c])
    elsif (st.size() > 0 && (c == ')' || c == ']') && rev[c] == st.last[1])
        seq.push(st.last)
        seq.push([i, c])
        st.pop
    else
        while (st.size() > 0)
            st.pop
        end
    end
    i += 1
end
seq.sort!
res = "", mx = -1, prv = -1, c = 0, t = ""
for i in seq
    # puts "#{i[0]} #{i[1]}"
    if (i[0] - prv == 1)
        c += 1 if (i[1] == '[')
        t << i[1]
    else
        if (mx < c)
            mx = c
            res = t.dup
        end
        t.clear
        c = 0
        c += 1 if (i[1] == '[')
        t << i[1]
    end
    prv = i[0]
end

if (mx < c)
    mx = c
    res = t.dup
end
puts mx, res

s = gets.chomp
st = []
seq = []
rev = {}
rev[')'] = '('
rev[']'] = '['
i = 0
s.each_char do |c|
    if (c == '(' || c == '[')
        st.push([i, c])
    elsif (st.size() > 0 && (c == ')' || c == ']') && rev[c] == st.last[1])
        seq.push(st.last)
        seq.push([i, c])
        st.pop
    else
        while (st.size() > 0)
            st.pop
        end
    end
    i += 1
end
seq.sort!
res = "", mx = -1, prv = -1, c = 0, t = ""
for i in seq
    # puts "#{i[0]} #{i[1]}"
    if (i[0] - prv == 1)
        c += 1 if (i[1] == '[')
        t << i[1]
    else
        if (mx < c)
            mx = c
            res = t.dup
        end
        t.clear
        c = 0
        c += 1 if (i[1] == '[')
        t += i[1]
    end
    prv = i[0]
end

if (mx < c)
    mx = c
    res = t.dup
end
puts mx, res

s = gets.chomp
st = []
seq = []
rev = {}
rev[')'] = '('
rev[']'] = '['
i = 0
s.each_char do |c|
    if (c == '(' || c == '[')
        st.push([i, c])
    elsif (st.size() > 0 && (c == ')' || c == ']') && rev[c] == st.last[1])
        seq.push(st.last)
        seq.push([i, c])
        st.pop
    else
        while (st.size() > 0)
            st.pop
        end
    end
    i += 1
end
seq.sort!
res = "", mx = -1, prv = -1, c = 0, t = ""
for i in seq
    # puts "#{i[0]} #{i[1]}"
    if (i[0] - prv == 1)
        c += 1 if (i[1] == '[')
        t << i[1]
    else
        if (mx < c)
            mx = c
            res = t.dup
        end
        t = ""
        c = 0
        c += 1 if (i[1] == '[')
        t += i[1]
    end
    prv = i[0]
end

if (mx < c)
    mx = c
    res = t.dup
end
puts mx, res

#!/usr/bin/ruby

s = STDIN.readline.strip + '$'
parens, brackets = [], []
left, right = 0, 0
count, best_count = 0, 0
best_left, best_right = 1, 0
while right < s.length
	ch = s[right]
	error = false
	if ch == '('
		parens.push(right)
	elsif ch == '['
		brackets.push(right)
		count += 1
	elsif ch == ')'
		if parens.length == 0
			error = true
		elsif brackets.length != 0 and brackets[-1] > parens[-1]
			error = true
		else
			parens.pop
		end
	elsif ch == ']'
		if brackets.length == 0
			error = true
		elsif parens.length != 0 and parens[-1] > brackets[-1]
			error = true
		else
			brackets.pop
		end
	else
		error = true
	end
	if not error
		if parens.length == 0 and brackets.length == 0
			if count > best_count
				best_count, best_left, best_right = count, left, right
			end
		end
		right += 1
	else
		while left != right
			if parens.length == 0 and brackets.length == 0
				if count > best_count
					best_count, best_left, best_right = count, left, right-1
				end
			end
			if s[left] == '('
				parens.shift
			elsif s[left] == '['
				brackets.shift
				count -= 1
			end
			left += 1
		end
		parens = []
		brackets = []
		left = right = right+1
		count = 0
	end
end
puts best_count
puts s[best_left..best_right]

#!/usr/bin/ruby

s = STDIN.readline.strip + '$'
parens, brackets = [], []
left, right = 0, 0
count, best_count = 0, 0
best_left, best_right = 1, 0
while right < s.length
	ch = s[right]
	error = false
	if ch == '('
		parens.push(right)
	elsif ch == '['
		brackets.push(right)
		count += 1
	elsif ch == ')'
		if parens.length == 0
			error = true
		elsif brackets.length != 0 and brackets[-1] > parens[-1]
			error = true
		else
			parens.pop
		end
	elsif ch == ']'
		if brackets.length == 0
			error = true
		elsif parens.length != 0 and parens[-1] > brackets[-1]
			error = true
		else
			brackets.pop
		end
	else
		error = true
	end
	if not error
		right += 1
	else
		while left != right
			if parens.length == 0 and brackets.length == 0
				if count > best_count
					best_count, best_left, best_right = count, left, right-1
				end
			end
			if s[left] == '('
				parens.shift
			elsif s[left] == '['
				brackets.shift
				count -= 1
			end
			left += 1
		end
		left = right = right+1
		count = 0
	end
end
puts best_count
puts s[best_left..best_right]

#!/usr/bin/ruby

s = STDIN.readline.strip + '$'
parens, brackets = [], []
left, right = 0, 0
count, best_count = 0, 0
best_left, best_right = 1, 0
while right < s.length
	#puts 'left = %d, right = %d, count = %d, brackets = %s, parens = %s' % [
	#		left, right, count, brackets, parens]
	ch = s[right]
	error = false
	if ch == '('
		parens.push(right)
	elsif ch == '['
		brackets.push(right)
		count += 1
	elsif ch == ')'
		if parens.length == 0
			error = true
		elsif brackets.length != 0 and brackets[-1] > parens[-1]
			error = true
		else
			parens.pop
		end
	elsif ch == ']'
		if brackets.length == 0
			error = true
		elsif parens.length != 0 and parens[-1] > brackets[-1]
			error = true
		else
			brackets.pop
		end
	else
		error = true
	end
	if not error
		if parens.length == 0 and brackets.length == 0
			if count > best_count
				best_count, best_left, best_right = count, left, right
			end
		end
		right += 1
	else
		next_left = right+1

		# find the longest correct substring preceding the error
		seek = right-1
		b, p, count = 0, 0, 0
		while seek >= left
			ch = s[seek]
			if ch == '['
				b -= 1
				count += 1
			elsif ch == ']'
				b += 1
			elsif ch == '('
				p -= 1
			elsif ch == ')'
				p += 1
			end
			if b == 0 and p == 0 and count > best_count
				best_count, best_left, best_right = count, seek, right
			end
			if b < 0 or p < 0
				b, p, count = 0, 0, 0
			end
			seek -= 1
		end

		parens, brackets = [], []
		left = right = next_left
		count = 0
	end
end
puts best_count
puts s[best_left..best_right]

#!/usr/bin/ruby

s = STDIN.readline.strip + '('
parens, brackets = [], []
left, right = 0, 0
count, best_count = 0, 0
best_left, best_right = 1, 0
while right < s.length
	ch = s[right]
	complete, error = false, false
	if ch == '('
		parens.push(right)
	elsif ch == '['
		brackets.push(right)
		count += 1
	elsif ch == ')'
		if parens.length == 0
			error = true
		elsif brackets.length != 0 and brackets[-1] > parens[-1]
			error = true
		else
			parens.pop
			complete = true if parens.length == 0 and brackets.length == 0
		end
	elsif ch == ']'
		if brackets.length == 0
			error = true
		elsif parens.length != 0 and parens[-1] > brackets[-1]
			error = true
		else
			brackets.pop
			complete = true if parens.length == 0 and brackets.length == 0
		end
	end
	if not complete and not error
		right += 1
		next
	end
	if complete
		if count > best_count
			best_count, best_left, best_right = count, left, right
		end
	elsif error
		while left != right
			if parens.length == 0 and brackets.length == 0
				if count > best_count
					best_count, best_left, best_right = count, left, right-1
				end
			end
			if s[left] == '('
				parens.shift
			elsif s[left] == '['
				brackets.shift
				count -= 1
			end
			left += 1
		end
	end
	left = right = right+1
	count = 0
end
puts best_count
puts s[best_left..best_right]

#!/usr/bin/ruby

s = STDIN.readline.strip + '$'
parens, brackets = [], []
left, right = 0, 0
count, best_count = 0, 0
best_left, best_right = 1, 0
while right < s.length
	ch = s[right]
	error = false
	if ch == '('
		parens.push(right)
	elsif ch == '['
		brackets.push(right)
		count += 1
	elsif ch == ')'
		if parens.length == 0
			error = true
		elsif brackets.length != 0 and brackets[-1] > parens[-1]
			error = true
		else
			parens.pop
		end
	elsif ch == ']'
		if brackets.length == 0
			error = true
		elsif parens.length != 0 and parens[-1] > brackets[-1]
			error = true
		else
			brackets.pop
		end
	else
		error = true
	end
	if not error
		if parens.length == 0 and brackets.length == 0
			if count > best_count
				best_count, best_left, best_right = count, left, right
			end
		end
		right += 1
	else
		while left != right
			if parens.length == 0 and brackets.length == 0
				if count > best_count
					best_count, best_left, best_right = count, left, right-1
				end
				break
			end
			if s[left] == '('
				parens.shift
			elsif s[left] == '['
				brackets.shift
				count -= 1
			end
			left += 1
		end
		parens = []
		brackets = []
		left = right+1
		right = right+1
		count = 0
	end
end
puts best_count
puts s[best_left..best_right]

#!/usr/bin/ruby

s = STDIN.readline.strip + '$'
parens, brackets = [], []
left, right = 0, 0
count, best_count = 0, 0
best_left, best_right = 1, 0
while right < s.length
	#puts 'left = %d, right = %d, count = %d, brackets = %s, parens = %s' % [
	#		left, right, count, brackets, parens]
	ch = s[right]
	error = false
	if ch == '('
		parens.push(right)
	elsif ch == '['
		brackets.push(right)
		count += 1
	elsif ch == ')'
		if parens.length == 0
			error = true
		elsif brackets.length != 0 and brackets[-1] > parens[-1]
			error = true
		else
			parens.pop
		end
	elsif ch == ']'
		if brackets.length == 0
			error = true
		elsif parens.length != 0 and parens[-1] > brackets[-1]
			error = true
		else
			brackets.pop
		end
	else
		error = true
	end
	if not error
		if parens.length == 0 and brackets.length == 0
			if count > best_count
				best_count, best_left, best_right = count, left, right
			end
		end
		right += 1
	else
		next_left = right+1

		# find the longest correct substring preceding the error
		right -= 1
		right -= 1 while right != left and s[right] != ']'
		if right != left
			b, p, count = 0, 0, 0
			seek = right
			while seek >= left
				ch = s[seek]
				if ch == '['
					b -= 1
					count += 1
				elsif ch == ']'
					b += 1
				elsif ch == '('
					p -= 1
				elsif ch == ')'
					p += 1
				end
				if b == 0 and p == 0 and count > best_count
					best_count, best_left, best_right = count, seek, right
				end
				break if b < 0 or p < 0
				seek -= 1
			end
		end

		parens, brackets = [], []
		left = right = next_left
		count = 0
	end
end
puts best_count
puts s[best_left..best_right]

#!/usr/bin/ruby

s = STDIN.readline.strip + '$'
parens, brackets = [], []
left, right = 0, 0
count, best_count = 0, 0
best_left, best_right = 1, 0
best_case = nil
while right < s.length
	ch = s[right]
	error = false
	if ch == '('
		parens.push(right)
	elsif ch == '['
		brackets.push(right)
		count += 1
	elsif ch == ')'
		if parens.length == 0
			error = true
		elsif brackets.length != 0 and brackets[-1] > parens[-1]
			error = true
		else
			parens.pop
		end
	elsif ch == ']'
		if brackets.length == 0
			error = true
		elsif parens.length != 0 and parens[-1] > brackets[-1]
			error = true
		else
			brackets.pop
		end
	else
		error = true
	end
	if not error
		if parens.length == 0 and brackets.length == 0
			if count > best_count
				best_count, best_left, best_right = count, left, right
				best_case = 0
			end
		end
		right += 1
	else
		while left != right
			if parens.length == 0 and brackets.length == 0
				if count > best_count
					best_count, best_left, best_right = count, left, right-1
					best_case = 1
				end
				break
			end
			if s[left] == '('
				parens.shift
			elsif s[left] == '['
				brackets.shift
				count -= 1
			end
			left += 1
		end
		parens = []
		brackets = []
		left = right+1
		right = right+1
		count = 0
	end
end
if s[best_left..best_right] == ']][[[[[]'
	puts 'best_case == %d' % best_case
end
puts best_count
puts s[best_left..best_right]

#!/usr/bin/ruby

s = STDIN.readline.strip + '$'
parens, brackets = [], []
left, right = 0, 0
count, best_count = 0, 0
best_left, best_right = 1, 0
while right < s.length
	ch = s[right]
	error = false
	if ch == '('
		parens.push(right)
	elsif ch == '['
		brackets.push(right)
		count += 1
	elsif ch == ')'
		if parens.length == 0
			error = true
		elsif brackets.length != 0 and brackets[-1] > parens[-1]
			error = true
		else
			parens.pop
		end
	elsif ch == ']'
		if brackets.length == 0
			error = true
		elsif parens.length != 0 and parens[-1] > brackets[-1]
			error = true
		else
			brackets.pop
		end
	else
		error = true
	end
	if not error
		if parens.length == 0 and brackets.length == 0
			if count > best_count
				best_count, best_left, best_right = count, left, right
			end
		end
		right += 1
	else
		while left != right
			if parens.length == 0 and brackets.length == 0
				if count > best_count
					best_count, best_left, best_right = count, left, right-1
				end
			end
			if s[left] == '('
				parens.shift
			elsif s[left] == '['
				brackets.shift
				count -= 1
			end
			left += 1
		end
		left = right = right+1
		count = 0
	end
end
puts best_count
puts s[best_left..best_right]

s = gets.chomp
st = []
seq = []
rev = {}
rev[')'] = '('
rev[']'] = '['
i = 0
s.each_char do |c|
    if (c == '(' || c == '[')
        st.push([i, c])
    elsif (st.size() > 0 && (c == ')' || c == ']') && rev[c] == st.last[1])
        seq.push(st.last)
        seq.push([i, c])
        st.pop
    else
        while (st.size() > 0)
            st.pop
        end
    end
    i += 1
end
seq.sort!
res = "", mx = -1, prv = -1, c = 0, t = ""
for i in seq
    # puts "#{i[0]} #{i[1]}"
    if (i[0] - prv == 1 || prv == -1)
        c += 1 if (i[1] == '[')
        t += i[1]
    else
        if (mx < c)
            mx = c
            res = t.dup
            t = ""
            c = 0
            c += 1 if (i[1] == '[')
            t += i[1]
        end
    end
    prv = i[0]
end

if (mx < c)
    mx = c
    res = t.dup
end
puts mx, res